Every now and then Python amazes me with its features. It is one programming language which captures the nuances of most of the programming styles of computation. Here we discuss functional programming with python to make your code more compact and use expression evaluation than execute a number of statements.
What is Functional Programming?
Functional programming is a paradigm in of programming which models the computation of expressions. Programs are executed as expressions rather than a number of statements, which do not allow state change as in imperative programming. Python does not strictly stick to functional programming but has some flavors of functional programming to it.
Functional programming requires functions which are First-class. They are nothing but functions that are treated like any other values and can be passed as
arguments to other functions or be returned as a result of a function.
Being first-class also means that it is possible to define and
manipulate functions from within other functions. Eg of a code i implemented for map function :-
def f(s): return s.upper()
def my_map(f,s):
result = []
for r in s:
temp = f(r)
result.append(temp)
return result
>>>s=['anjali','menon']
>>> my_map(f,s) => ['ANJALI','MENON']
def my_map(f,s):
result = []
for r in s:
temp = f(r)
result.append(temp)
return result
>>>s=['anjali','menon']
>>> my_map(f,s) => ['ANJALI','MENON']
Instead of upper you can define any function for f and any list for s and the function is applied to each element in the given list.
Pure Functions
According to Wikipedia and i quote:-
"In computer programming, a function may be described as pure if both these statements about the function hold:
"In computer programming, a function may be described as pure if both these statements about the function hold:
- The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change as program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices.
- Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices." Eg:-
def length(s): return len(s)
The length of the string remains the same no matter how many times you call the function length(). It only varies if you vary the input.
Referential Transparency
Pure functions yield the same value each time they are invoked. This property is referential transparency and makes possible to conduct equation reasoning on the code-
if y = f x and g = h y y then we should get the same result for g = h fx fx.
What are higher order functions?
Higher order functions are functions that take other functions as their parameters.Higher-order functions are very useful for refactoring code and reduce the amount of repetition. For example, typically most for loops can be expressed using maps. A function is considered as a mechanism for capturing patterns. Eg:-
def add(x,y):
if x > y: return 0
else: return x + add(x+1,y)
Python allows the use of lambda. It is a keyword used for making anonymous functions. According to Wikipedia an anonymous function (also function constant or function literal) is a function (or a subroutine) defined, and possibly called, without being bound to an identifier. Anonymous functions are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions. The lambda function should contain expressions only. Usually use of lambda while writing codes should not be done frequently. The idea is to simply write a code in lambda, think about the basic idea in the function or the best use of the function and replace lambda with def functionname!
Eg:-
lambda x: x + 10
The are other simple functions which can be used to make your code more compact and less complicated. The use of map we can simply apply the function in map to every element given in the list.Eg:-
def cube(x): x*x*x
map(cube, [2,4,6,8])=> [8,64,216,512]
The next one is filter, which allows to filter out the values which satisfy the expression given in the function. Also we have filterfalse which returns the opposite of filter.Eg:-
filter(lambda x: x%3 == 0 in range(10))=> [3,6,9]
filterfalse(lambda x: x%3 == 0 in range(10))=>[1,2,4,5,7,8]
Another one is reduce which applies the function within the list and returns the result.Eg:-
reduce(operator.add, [1,2,3],0)=> 6
where in a file operator.py add function is defined.
What is closure and currying?
Closures allow functions to be nested within other functions. The value passed to functions are within parenthesis indicating the value is parsed to functions in the order the appear. Eg:-
def mul(a): return lambda (b): a*b
called as mul(3)(4) returns 12.
Currying is a technique by which if a function takes multiple arguments then it can be called as a chain of functions that take single arguments. This means that we can define a function say f(x,y) = x*y and make it as g(y) = f(2,y)= 2*y
then replace y with 3 we have g(3)= f(2,3) = 2*3
Eg:-
def add_2(a): return add_1(b): a+b
called as add_2(3)(4) results in 7.
Python with functional programming style lessens the number of lines of code, helps in applying the built in function with less hassle and more efficiency.
No comments:
Post a Comment