Exercise 2.4
#lang racket
(define (cons x y)
(lambda (m) (m x y)))
(define (car z)
(z (lambda (p q) p)))
;(cons x y) return a procedure (lambda (m) (m x y))
;that takes a procedure m as argument and calls it on its two own arguments.
;so,we pass m the procedure (lambda (p q) p) which need two paramters
;hence,it applys x->p,y->q,and produces the result x.
;the cdr procedure
(define (cdr z)
(z (lambda (p q) q)))
Exercise 2.5
#lang racket
;can b divide by a?
(define (divide? a b)
(= (remainder b a) 0))
;expt need two arguments,one is base
(define (my-cons a b)
(* (expt 2 a) (expt 3 b)))
;get exponent a
(define (my-car c)
(define (mid-car c n)
(cond ((not (divide? 2 c)) n)
(else (mid-car (/ c 2) (+ n 1)))))
(mid-car c 0))
;get exponent b
(define (my-cdr c)
(define (mid-car c n)
(cond ((not (divide? 3 c)) n)
(else (mid-car (/ c 3) (+ n 1)))))
(mid-car c 0))
Exercise 2.6
#lang racket
;zero-fold combination f on x
(define zero
(lambda (f)
(lambda (x)
x)))
(define (add-1 n)
(lambda (f)
(lambda (x)
(f ((n f) x)))))
;one-fold combination f on x
(define one
(lambda (f)
(lambda (x)
(f x))))
;two-fold combination f on x
(define two
(lambda (f)
(lambda (x)
(f (f x)))))
;(a+b)-fold combination f on x
(define (add a b)
(lambda (f)
(lambda (x) ((a f) ((b f) x)))))
Summarize
- 书中提到的message passing方法,就像一个调度器,使我们可以在一个方法里实现很多任务,使程序更好的模块化。
- 方法即数据?确实很让人困惑,但是书中示例中的方法确实满足了数据的要求。更进一步看,Lisp是可以传递方法的,这种强大的语言特性,不仅使我们可以抽象各种各样的通用操作,更是我们可以用方法解释方法成为现实,或者说,更直接一些(在面向对象的语言中,我们传递的数据是对象,其实更是对象中数据跟方法)。