I am trying to learn Functional Programming, and I am doing so with Python. An exercise I am trying do is to make a function that returns true if a number is even.
def evenOrOdd(x):
return lambda x: x%2 == 0
print(evenOrOdd(1))
print(evenOrOdd(2))
print(evenOrOdd(3))
print(evenOrOdd(4))
<function evenOrOdd.<locals>.<lambda> at 0x7f7a9a145670>
<function evenOrOdd.<locals>.<lambda> at 0x7f7a9a145670>
<function evenOrOdd.<locals>.<lambda> at 0x7f7a9a145670>
<function evenOrOdd.<locals>.<lambda> at 0x7f7a9a145670>
This is what I have at the moment, but as you see, it is not returning a boolean.
You either do this: (declaring a normal function)
def evenOrOdd(x):
return x%2 == 0
or this: (declaring a function using a lambda)
evenOrOdd = lambda x: x%2 == 0
This
def evenOrOdd(x):
return lambda x: x%2 == 0
means you are returning a lambda function from the function evenOrOdd
. In this case the variable x makes no actual difference, since the lambda redefines it. You could call it like so:
evenOrOdd(999)(2) #999 could be anything