Exercise 2.4

Read Exercise 2.4 ~ Solution


When I first read about defining cons, car and cdr procedurally, I had my first lisp wow moment.

(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)))

(define test-pair (cons 3 4))
; what kind of beast are we dealing with
test-pair
# 
(car test-pair)
3
(cdr test-pair)
4

(cdr (cons x y))
(z (lambda (p q) q))
z = (cons x y) = (lambda (m) (m x y))
-> ((lambda (m) (m x y)) (lambda (p q) q))
-> ((lambda (p q) q) x y)
-> y

One thought on “Exercise 2.4

  1. The most exciting part is that it takes the second lambda function as the ‘m’ value for the first lambda. This procedure combined almost everything we learned by now!

Leave a comment