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?
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.
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.
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.
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.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With