functional programming in Python
Higher order functions
a higher order function is a function that passes a function as a parameter. It's a bit like a delegate in C #, personally.
def Add (x,y,f): return f (x) + f (y) print Add ( -18,11,abs)
It will do so:
ABS ( -18) + ABS (11)
The result would be:
29
map () function
map () is a Python built-in high-order function that receives a function f and a list, and then, by putting the function f on each element of the list in turn, gets a new list and returns.
def f (x): return x* xprint#every element in the list will go through the f (X) method
The result will be:
[1, 4, 9, 10, 25, 36, 49]
reduce () functionthe
reduce () function is also a high-order function built into Python. The reduce () function receives a parameter similar to map (),
a function f, a list, but behaves differently from map (), and reduce () the incoming function f must receive two parameters, and reduce () calls function f repeatedly on each element of the list, and returns the final result value.
def f (x, y): return x* y print#1*2*3*4
The result will be this:
24
What if you want to give the initial value? Need this:
def F (A, B ): return a + bprint#1+2+3+4+10. The third parameter here is the initial value.
The result would be:
20
filter () functionThe
filter () function is another useful high-order function built into Python, and the filter () function receives a
function f and a
list, the function of which is to judge each element and return True or False,
filter () automatically filters out non-conforming elements based on the result of the decision, returning a new list of eligible elements.
def is_odd (x): return x%2==1 Print filter (is_odd,[1,2,3,4,5,6,7])
The result is:
[1, 3, 5, 7]
Custom Sort Functions
The python built-in sorted () function can sort the list:
Sorted ([36, 5, 12, 9, 21])
[5, 9, 12, 21, 36]
But sorted () is also a high-order function, which can receive a comparison function to implement a custom sort, the definition of the comparison function is to pass in two elements to be compared x, Y, if x should be in front of y, return-1, if X should be ranked after Y, return 1. returns 0 if x and y are equal.
Functional programming in Python