Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 834
4tlulz Avatar asked Feb 08 '11 04:02

4tlulz


People also ask

What does cons do in scheme?

The other constructor, cons , is used when you already have a list and you want to add one new element. Cons takes two arguments, an element and a list (in that order), and returns a new list whose car is the first argument and whose cdr is the second.

What is a list in Scheme?

In contrast to Scheme's unstructured data types, such as symbols and numbers, lists are structures that contain other values as elements. A list is an ordered collection of values. In Scheme, lists can be heterogeneous, in that they may contain different kinds of values.

What are closures in Scheme?

Scheme procedure's aren't really just pieces of code you can execute; they're closures. A closure is a procedure that records what environment it was created in. When you call it, that environment is restored before the actual code is executed.

What is lambda in scheme?

Lambda is the name of a special form that generates procedures. It takes some information about the function you want to create as arguments and it returns the procedure. It'll be easier to explain the details after you see an example.


1 Answers

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."

like image 129
Jeremiah Willcock Avatar answered Sep 27 '22 00:09

Jeremiah Willcock