Church计数

my code:

 

 1 ;Church计数
2
3 (define zero (lambda (f) (lambda (x) x)))
4 (define (add-1 n) (lambda (f) (lambda (x) (f ((n f) x)))))
5 (define (show-num n)((n (lambda (x) (+ 1 x))) 0))
6 (define (add a b) (lambda (f) (lambda (x) ((a f) ((b f) x)))))
7 (define one (lambda (f) (lambda (x) (f x))))
8 (define two (lambda (f) (lambda (x) (f (f x)))))
9
10 (show-num zero)
11 (show-num one)
12 (show-num two)
13 (newline)
14 (show-num (add-1 zero))
15 (show-num (add-1 (add-1 zero)))
16 (show-num (add-1 (add-1 (add-1 zero))))
17 (show-num (add-1 (add-1 (add-1 (add-1 zero)))))
18
19 (newline)
20 (display "my add\n")
21 (show-num (add zero zero))
22 (show-num (add (add-1 zero) (add-1 zero)))
23 (show-num (add (add-1 zero) (add-1 (add-1 zero))))
24
25 (define (multi a b)
26 (lambda (f)
27 (lambda (x)
28 ((a (b f) ) x))))
29
30 (define (expon a b)
31 (lambda (f)
32 (lambda (x)
33 (((a b) f) x))))
34
35 (show-num (multi two two))
36 (show-num (multi (add one two) two))
37
38 (show-num (expon two two))
39 (show-num (expon (expon two two) two))



Church计数,通过(lambda (f))把f作为参数,这样f就不会被求值,而f的执行次数就代表了数字。

lambda中的形参其值是未知的,所以不会被求值。

形参好比糖果的包装纸,要把一段代码包起来,把它放到一个匿名函数里就行了

比如有一个函数

(lambda (a b) (+ a b))

要把它包装起来,可以写成

(lambda (x) (lambda (a b) (+ a b)) )

要剥开糖纸,传个参数就行了。

Church计数就是这个思想。

show-num用来把Church计数方式的数字转换成普通数字。

posted on 2011-11-21 00:24  windydays  阅读(591)  评论(1编辑  收藏  举报

导航