Day #5: Functional Programming with Python.
3 min read
Hey. Hope you have been enjoying the series so far. Today is the Day 5 of the #100DaysOfCodeChallenge. Received a problem previously asked by Jane Street (refer the hyperlink for the company details) with a medium tag to it. This question is a true puzzle and can be solved in a minute if your functional programming understanding is strong.
You may get confused with the question, just like the way I did. I will try my best in putting the solution in the simplest way possible. You can always reach out to me if you need help.
The Question On Day #5:
cons(a, b) constructs a pair, and
cdr(pair) returns the first and last element of that pair. For example,
car(cons(3, 4)) returns
cdr(cons(3, 4)) returns
Given this implementation of cons:
def cons(a, b): def pair(f): return f(a, b) return pair
The question is a bit confusing but let us try to understand it clearly.
consis a function which takes two inputs (consider integers). It returns a value which is an function defined inside itself, i.e.
pairis a function which takes a function
fas input and returns the return value of its input function, i.e. the return value of the function
fis returned by
fis a function which will return a value.
fis the key to all our solution.
- The end value obtained on calling the function cons is a function pointer pointing to the
- The required implementation goes as follows:
Output 3 4
car(cons(3,4)) is called,
- cons(3,4) is invoked in the first place.
- cons returns the function pair function.
- The parameter passed to the
carfunction is the
carfunction returns the value returned by calling the
pairfunction takes a function as input, so we pass the
leftfunction to it.
pairfunction returns the value obtained by passing a, b to a a function
f. So, our
leftis the function
f, which takes a, b as input and returns a as output to the
- Now the same a is returned by
pairfunction to the
carfunction, which will again return the same value of a.
- Now a is returned at the end and printed.
- Same goes with the function
#The Python visualiser is very much needed to understand this logic more clearly, please refer it here.
I hope you were able to understand this problem. Feel free to reach out for any query clearance.
Thanks and cheers:)