Beauty of Lambdas
The Challenge⌗
I came across an interesting kata on Codewars.
This task should not be any problem for a seasoned functional programmer.
Rookies however might shed some sweat while working out the solution.
The key is in realization that a function call does not have to return just a number/string/object... but it can return a function as well.
Plus, if you were not familiar with lambdas in Python, now, after finising the kata, you are.
Warning:
Spoiler alert: If you would like to figure out the solution yourself, stop right here.
The solution⌗
This is the simplest solution. Of course, the code is not ideal, you have a function for each number. There is a more universal approach but that is out of scope of this post.
def identity(x): return x
def zero(f=identity): return f(0)
def one(f=identity): return f(1)
def two(f=identity): return f(2)
def three(f=identity): return f(3)
def four(f=identity): return f(4)
def five(f=identity): return f(5)
def six(f=identity): return f(6)
def seven(f=identity): return f(7)
def eight(f=identity): return f(8)
def nine(f=identity): return f(9)
def plus(y): return lambda x: x+y
def minus(y): return lambda x: x-y
def times(y): return lambda x: x*y
def divided_by(y): return lambda x: x/y
From the solutions, it is also possible to simplify the definition of the 'numbers'
id_ = lambda x: x
number = lambda x: lambda f=id_: f(x)
zero, one, two, three, four, five, six, seven, eight, nine = map(number, range(10))
How it works⌗
res = seven(times(five())) #35
five()
returns
f(5) = identity(5) = 5
times(5)
returns a function
x: x*5
seven(x: x*5)
does
f(7) = 7*5 = 35
A simple yet elegant reminder of higher order functions.