【问题标题】:Is it possible to define subtraction in Primitive Recursion without a predecessor function?是否可以在没有前置函数的情况下在原始递归中定义减法?
【发布时间】:2012-11-13 13:44:17
【问题描述】:

我有一个任务,我正在编写一堆基本的原始递归函数,其中一个是减法。我没有得到前任的定义,我认为我不太可能将其定义为eval Pred [x] = x-1。下面是我对 PR 的定义,我还定义了几个其他函数,例如时间、AND、OR、NOT、pow、true、false 和 ite。是否可以只用我这里的东西来定义减法?如果是这样,有人可以给我一些指导。我目前的想法是我可以做类似的事情,给定 minus[x,y] recurse y 次然后返回 P 2 。如果y > x 我应该返回零。以下是我对 PR 的定义。

 import Prelude hiding (pred,and,or,not)

 data PR = Z
     | S
     | P Int
     | C PR [PR]
     | PR PR PR
     deriving Show
 eval :: PR -> [Integer] - Integer
 eval Z _ = 0
 eval S [x] = x+1
 eval (P n) xs = nth n xs
 eval (C f gs) xs = eval f (map (\g -> eval g xs) gs)
 eval (PR g h) (0:xs) = eval g xs
 eval (PR g h) (x:xs) = eval h ((x-1) : eval (PR g h) ((x-1):xs) : xs)

 nth _ [] = error "nth nil"
 nth 0 _ = error "nth index"
 nth 1 (x:_) = x
 nth (n) (_:xs) = nth (n-1) xs

 one = C S [Z]
 plus = PR (P 1) (C S [P 2])

编辑;我发现我的问题在于定义正确的基本情况。 PR (P 3) (P 1) 返回P 1 - 1,这是朝着正确方向迈出的一步,但是,我需要递归P 3 次。我在想像PR (PR Z (P 3)) (P 1) 这样的东西会做到这一点。这当然是不正确的,但想法是从P 3 递归到ZP 1 每次递减。

【问题讨论】:

    标签: haskell recursion computation-theory


    【解决方案1】:

    我意识到这样做的方法是使用 PR 定义前任。

    pred = PR Z (P 1)
    

    如果x = 0,则返回x-1 或零。

    从那里可以定义如下方式

    modus = C modus' [P 2, P 1]
    modus' = PR P 1 (C pred [P 2])
    

    递归递减P 1P 2 次或直到P 1 等于零。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2018-01-03
      • 2010-10-04
      • 2012-09-14
      相关资源
      最近更新 更多