1

I can't seem to explain how this definition of cons, car and cdr works:

(define (p-cons x y)
   (lambda (proc) (proc x y)))

(define (p-car proc)
   (proc (lambda (p q) p)))

(define (p-cdr proc)
   (proc (lambda (p q) q)))

I understand that the first procedure returns a procedure which takes a procedure as an argument, and applies this procedure to the two arguments x y. What I don't understand is how car and cdr works:

(p-car (p-cons "foo" "bar")) -> foo
(p-cdr (p-cons "foo "bar")) -> bar

If someone could explain how this works I would appreciate it! How does the lambda-expression in 'car' and 'cdr' get the 'p' and 'q' variables for exemple?

user16655
  • 1,901
  • 6
  • 36
  • 60
  • I think this has been descibed in another answer – Joshua Taylor May 29 '15 at 12:20
  • This might be a duplicate of [Use of lambda for cons/car/cdr definition in SICP](http://stackoverflow.com/q/21769348/1281433). – Joshua Taylor May 29 '15 at 12:20
  • Or of [Re-implementing lists with closures in scheme](http://stackoverflow.com/q/27111724/1281433) – Joshua Taylor May 29 '15 at 12:21
  • I think that the first of those linked duplicates is probably the most useful for you. – Joshua Taylor May 29 '15 at 12:27
  • use better, more suggestive names, like `(define (p-cons x y) (lambda (sel) (sel x y)))`. Now it is plain that `(p-cons x y)` creates a procedure that expects a selector procedure, and passes it the two arguments that were given to `p-cons`. Then `car` just supplies the selector of the 1st argument, and `p-cdr` - of the second argument. – Will Ness Jun 01 '15 at 20:42

1 Answers1

2

Just do a substitution:

(p-car (p-cons "foo" "bar"))

;substituting p-cons:
(p-car (lambda (proc) (proc "foo" "bar")))

;substituting p-car:
((lambda (proc) (proc "foo" "bar")) (lambda (p q) p))

((lambda (p q) p) "foo" "bar")

"foo"

And similarly for p-cdr.

Essentially p-cons just creates a lambda which expects a procedure which will pick the appropriate stored value. p-car picks the first, p-cdr the second.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Thank you so much! I can't believe I haven't thought of using the substitution model before, I have spent a really long time trying to understand this. – user16655 May 29 '15 at 13:04