Daily Coding Problem: Problem #5
Problem
This problem was asked by Jane Street.
cons(a, b)
constructs a pair, andcar(pair)
andcdr(pair)
returns the first and last element of that pair. For example,car(cons(3, 4))
returns3
, andcdr(cons(3, 4))
returns4
.Given this implementation of cons:
def cons(a, b):
def pair(f):
return f(a, b)
return pair
Implement
car
andcdr
Solution
The cons
function returns another function which takes a
and b
as parameters. The returned function pair
takes a function and invokes it with a
and b
as parameters. So inorder for car
and 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 car
and cdr
must define a function that will be used by the pair
function.
def car(f): # f is the pair function returned by function cons
return f(lambda a, b: a)
def cdr(f):
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!.