This problem was asked by Jane Street.
cons(a, b)constructs a pair, and
cdr(pair)returns the first and last element of that pair. For example,
Given this implementation of cons:
def cons(a, b):
return f(a, b)
cons function returns another function which takes
b as parameters. The returned function
pair takes a function and invokes it with
b as parameters. So inorder for
cdr to work as intended, these functions need to take a function as a parameter. Given a pair,
car must return the first element and
cdr must return the second element. So
cdr must define a function that will be used by the
def car(f): # f is the pair function returned by function cons
return f(lambda a, b: a)
return f(lambda a, b: b)
assert car(cons(3, 4)) == 3
assert cdr(cons(3, 4)) == 4
I hope you guys enjoyed this post.
If you find it helpful, please share and claps are much appreciated! 😄
Feel to ask your queries in the comments section!.