(define (make-rat n d)
(let ((sign (if (positive? (* n d)) 1 -1))
(abs-n (abs n))
(abs-d (abs d))
(g (gcd n d)))
(cons (* sign (/ abs-n g))
(/ abs-d g))))exercise 2.2
segment definition
(define (make-segment point-a point-b)
(cons point-a point-b))(define (start-segment seg)
(car seg))(define (end-segment seg)
(cdr seg))(define (midpoint-segment seg)
(make-point (average (x-point (start-segment seg))
(x-point (end-segment seg)))
(average (y-point (start-segment seg))
(y-point (end-segment seg)))))
(define (print-segment seg)
(newline)
(print-point (start-segment seg))
(display " -- ")
(print-point (end-segment seg)))point definition
(define (make-point x y)
(cons x y))(define (x-point p)
(car p))(define (y-point p)
(cdr p))(define (print-point p)
(display "(")
(display (x-point p))
(display ", ")
(display (y-point p))
(display ")"))exercise 2.4
(define (cons x y)
(lambda (m) (m x y)))(define (car z)
(z (lambda (p q) p)))(define (cdr z)
(z (lambda (p q) q)))Explain:
take car as an example:
the value of (car z) is that returned by (z (lambda (p q) p)), as defined.
it needs to first evalutate the operator and operand respectively.
the operator is a procedure generated by cons, (lambda (m) (m x y)),
the operand is also a procedure, (lambda (p q) p),
substitute m with the operand, clearly, the return value is p
exercise 2.6
the definition of zero
(define zero (lambda (f) (lambda (x) x)))is the same as:
(define (zero f) (lambda (x) x))so,
(define one (lambda (f) (lambda (x) (f x))))the same as:
(define (one f) (lambda (x) (f x)))(define two (lambda (f) (lambda (x) (f (f x)))))same as:
(define (two f) (lambda (x) (f (f x))))A number defined this way takes a procedure as argument, and also returns a procedure. The later one applies the former one N times to the later one's argument.
so the addition procedure (add m n) means applying M+N times.
(define (add m n)
(lambda (f)
(lambda (x)
((m f)
((n f) x)))))

0 comments:
Post a Comment