I was looking at this question:
cons(a, b)
constructs a pair, and car(pair)
and cdr(pair)
returns the first and last element of that pair. For example, car(cons(3, 4))
returns 3, and cdr(cons(3, 4))
returns 4.
Given this implementation of cons:
def cons(a, b):
def pair(f):
return f(a,b)
return pair
Implement car and cdr.
I recognised the lambda expression, but I'm still unsure of how it works. The answer is given as:
def car(f):
z = lambda x, y: x
return f(z)
def cdr(f):
z = lambda x, y: y
return f(z)
If f is the function object, isn't passing z to f calling lambda f : f(a,b)
, where z has 2 arguments but the other lambda only has 1 argument?
How does this solution work?