球拍。实现Ackermann的功能

时间:2015-03-02 21:06:39

标签: 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 = 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)

2 个答案:

答案 0 :(得分:1)

这是一个简单的翻译,你只需要使用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))

答案 1 :(得分: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)))]))