Racket 球拍实施阿克曼';s函数
我试图去理解,但到目前为止我还不能让自己明白。当我看到完成的解决方案时,更容易理解如何做。这是我的第一个练习,其他人想自己做,但需要了解如何实现它。 请帮我写一个球拍函数 实现Ackermann函数A。它采用两个参数x和y,工作如下:Racket 球拍实施阿克曼';s函数,racket,Racket,我试图去理解,但到目前为止我还不能让自己明白。当我看到完成的解决方案时,更容易理解如何做。这是我的第一个练习,其他人想自己做,但需要了解如何实现它。 请帮我写一个球拍函数 实现Ackermann函数A。它采用两个参数x和y,工作如下: if y = 0, then it returns 0; if x = 0, then it returns 2*y; if y = 1, then it returns 2; else, it calls itself (function A) with x =
if y = 0, then it returns 0;
if x = 0, then it returns 2*y;
if y = 1, then it returns 2;
else, it calls itself (function A) with x = x-1 and y = A ( x, (y - 1) )
给出了工程实例
#lang racket/base
(require rackunit)
;; BEGIN
;; END
(check-equal? (A 1 10) 1024)
(check-equal? (A 2 4) 65536)
(check-equal? (A 3 3) 65536)
这是一个简单的翻译,您只需使用Scheme的语法编写公式:
(define (A x y)
(cond ((= y 0) 0) ; if y = 0, then it returns 0
((= x 0) (* 2 y)) ; if x = 0, then it returns 2*y
((= y 1) 2) ; if y = 1, then it returns 2
(else (A (- x 1) ; else it calls itself (function A) with x = x-1
(A x (- y 1)))))) ; and y = A ( x, (y - 1))
这里有一个解决方案:
#lang racket
(define (ack x y)
(match* (x y)
[(_ 0) 0] ; if y = 0, then it returns 0
[(0 y) (* 2 y)] ; if x = 0, then it returns 2*y
[(_ 1) 2] ; if y = 1, then it returns 2
[(x y) (ack (- x 1) (ack x (- y 1)))]))
像往常一样,你试过什么?(定义(A x y)(cond((=y 0)0)(=x 0)(*2y)(=y 1)2)),然后我不懂如何做,所以你不懂的是递归调用。我不知道如何在这里写这部分(否则,它用x=x-1和y=A(x,(y-1))调用自己(函数A)这就是我直到最后才理解的语法。请寻求帮助,因为那样我会理解的。非常感谢。