sicp-answer~> 1-10

先贴代码:

(define (A x y) (cond 
  ((= y 0) 0)
  ((= x 0) (* 2 y))
  ((= y 1) 2)
  (else (A (- x 1)
           (A x (- y 1))))))

(A 1 10)
; 1024

(A 2 4)
; 65536

(A 3 3)
; 65536

(define (f n) (A 0 n))
(define (g n) (A 1 n))
(define (h n) (A 2 n))

你可以手动展开诸如 (A 1 10) 这样的代码, 当然, 也可以选择使用 racket/trace 中的 trace 来跟踪递归情况:

(require racket/trace)
(trace A)
(A 1 10)

会输出以下内容:

>(A 1 10)
> (A 1 9)
> >(A 1 8)
> > (A 1 7)
> > >(A 1 6)
> > > (A 1 5)
> > > >(A 1 4)
> > > > (A 1 3)
> > > > >(A 1 2)
> > > > > (A 1 1)
< < < < < 2
> > > > >(A 0 2)
< < < < <4
> > > > (A 0 4)
< < < < 8
> > > >(A 0 8)
< < < <16
> > > (A 0 16)
< < < 32
> > >(A 0 32)
< < <64
> > (A 0 64)
< < 128
> >(A 0 128)
< <256
> (A 0 256)
< 512
>(A 0 512)
<1024
1024