Help understanding this implementation of cons and car in scheme using lambdas

549 Views Asked by At

My question relates to the following code:

 (define (cons. x y)
   (lambda (m) (m x y)))

 (define (car. z)
   (z (lambda (p q) p)))

My problem is with how this code actually works. As far as I can understand cons. is returning a procedure containing the variables x and y within its scope. car. then takes the returned procedure from cons. and applies it to another lambda that takes two arguments p and q and returns p. My confusion lies within that second lambda, where exactly do the values of P and Q come from?

1

There are 1 best solutions below

0
On BEST ANSWER

The variables p and q are the two elements of the "cons cell"; i.e., they are the x and y in cons.. If you run (car. (cons. 1 2)), you get (expanding cons.):

(car. (lambda (m) (m 1 2))

which turns into (using the definition of car.):

((lambda (m) (m 1 2)) (lambda (p q) p))

Plugging the argument into the body of the first lambda, you get:

((lambda (p q) p) 1 2)

Another substitution like that gives you 1, the first element of the "cons cell."