尝试在方案中编写超操作

时间:2019-04-06 08:19:55

标签: algorithm scheme sicp

我正在尝试在MIT / GNU-Scheme中编写一个超级操作程序,但是遇到了一些麻烦,我已经编写了n = 5个工作的单个程序,但想使一个函数可以全部完成。我将在下面列出一些失败的尝试。

(define hyp (lambda (n x y)
  (hypiter n x x y)))
(define hypiter (lambda (lev an cou lim)
  (if (= lev 1) an
  (hypiter lev (hyp (- lev 1) an cou) cou lim))))
(define hyper (lambda (n x y)
  (hyper n x x y)))
(define hyperiter (lambda (lev an cou lim)
  (if (= lev 1) (+ an cou)
  (hyper (- lev 1) an cou))))
(define h (lambda (n a b)
  (cond
    ((= n 1) (+ a b))
    ((= b 1) (- n 1))
    (else (h (- n 1) (h (- n 1) a a) (- b 1)))))))
(define hyperoperation (lambda (n a b)
  (cond
    ((= n 0) (+ 1 b))
    ((and (= n 1) (= b 0)) a)
    ((and (= n 2) (= b 0)) 0)
    ((and (>= n 3) (= b 0)) 1)
    (else (hyperoperation (- b 1) a (hyperoperation n a (- b 1)))))))

1 个答案:

答案 0 :(得分:2)

根据wikipedia中的定义,上一个定义的最后一行有错误。应该是:

(else (hyperoperation (- n 1) a (hyperoperation n a (- b 1))))))

代替:

(else (hyperoperation (- b 1) a (hyperoperation n a (- b 1)))))))

因此可能的正确递归定义可能是:

(define (hyperoperation n a b)
  (cond ((= n 0) (+ b 1))
        ((= b 0) (cond ((= n 1) a)
                       ((= n 2) 0)
                       (else 1)))
        (else (hyperoperation (- n 1) a (hyperoperation n a (- b 1))))))