Sunday, 3 July 2011

Functional programming in python

     In python we can pass functions as an argument to another function. This is called higher order functions. Lets define two functions at the interactive python prompt and try some experiments.
>>> def sqr(x): return x*x
...
>>> def cube(x): return x*x*x
... 
>>> def compose(f,g,x): return f(g(x))
...
>>> compose(sqr,cube,3)
729
    In this example we define two functions sqr() and cube(), then we pass these functions as an argument to the another function compose(). Compose function perform the computstion and return the result.
    The functional programming paradigm encourages us to structure our programs as collections of pure functions. The basic element of Functional programming in python are the functions map(),reduce(),and filter() , and the operator lambda.
Lambda
The lambda keyword is used for creating anonymous functions. The body of the lambda should be composed of simple expressions only. More than one arguments are supported, these are separated by commas. Lambda is often used in conjunction with map(),filter() and reduce().
Syntax:
lambda argument_list:expression
Example:
>>> f=lambda x:x+4
>>> f(3)
7
In the above example, we use lambda to create a function which accepts an argument and returns it after adding four.
>>> f=lambda x,y:x+y
>>> f(5,4)
9
    In this example lambda take two arguments and return result after adding the values.
filter()
Filter function accepts a function and a list as arguments and returns the list composed of only those elements for which the function returns true.
syntax:
filter(function,sequence)
Example:
>>> a=[2,3,6,7,11]
>>> output=filter(lambda x:x%2,a)
>>> print output
[3, 7, 11]
Here function 'lambda' will be applied to every element of the list a. If the function return true for a particular list of elements, that will be included in the result list.
map()
Map function accepts a function and a list as arguments and returns the list obtained by applying the function on each element of the original list.
Syntax:
map(function,sequence)
Example
>>> def sqrt(x): return x*x
...
>>> map(sqrt,[2,6,3,1,9])
[4, 36, 9, 1, 81]
     map function accept a function sqrt and a list of elements, then it apply the function to each element of the list and retun the result list.
This example can also be written by using lambda.
>>> map(lambda x:x*x,[2,6,3,1,9])
[4, 36, 9, 1, 81]
reduce()
     Important thing is that, reduce() returns only a single value. It also accept a function and a list of elements, at first it take the first two elements in the list and applied it to the function, in the next step the result of the previous step and the next element is applied to the function, this process will continue at the end of the list, finally a single value returned.
Syntax:
reduce(function,sequence)
Consider the following example which uses reduce to compute the sum of a list of numbers.
Example
>>> nums=[1,2,3,10,20,30]
>>> def add(x,y): return x+y
...
>>> s=reduce(add,nums)
>>> print s
66
map – reduce
Note that the return value of a map is a list while the input of reduce is a list. Thus, the two functions can be combined to a great effect.
Example
>>> a=[1,2,3,10,200,3000]
>>> b=[20,30,40,10,3,2]
>>> def add(x,y):
... return x+y
...
>>> def mul(x,y):
... return x*y
...
>>> result=reduce(add,map(mul,a,b))
>>> print result
6900
     We don't actually have to define the add and mul function above. We can simply use operator.add and operator.mul from the operator module.
Example
>>> import operator
>>> A=[1,2,3,10,200,3000]
>>> B=[20,30,40,10,3,2]
>>> s=reduce(operator.add,map(operator.mul,A,B))
>>> print s
6900

Function

     In this post I want to share some basic concepts about the functions in python. I think this post is very useful for all who want to know the function in python.
     Functions are reusable pieces of programs. They allow you to give name to a block of statements and you can run that block using that name anywhere in your program and any number of times. Functions are defined using the def keyword. This keyword followed by the function name followed by a pair of parentheses which may enclose some names of variables and the lines ends with a colon. Next follows the block of statements that are part of this function.
Example:
def hello():
     print 'Hello World.'
Output
hello() # call the function
Hello World
Parameters
Parameters are specified within the pair of parentheses in the function definition, separated by commas. When we call the function, we supply the values in the same way. The names given in the function definition are called parameters. Whereas the values you supply in the function are called arguments.
Example1
>>> def max(a,b):
...         if a>b:
...             print a,' is maximum'
...         else:
...             print b,' is maximum'
Output
>>> max(7,5) # Directly give the literal values
7 is maximum
Example 2
>>> def max(a,b):
... if a>b:
... print a,' is maximum'
... else:
... print b,' is maximum'
Output
>>> x=5
>>> y=7
>>> max(x,y) # Give variables as arguments
7 is maximum
Local Variable
     Variables defined in the functions are not related to any other variables defined with the same name outside the function. That is the variable names are local to the function.
Example
>>> def fun(x):
...         print 'x is',x
...         x=5
...         print 'changed local x to',x
Output
>>> x=10
>>> fun(x)
x is 10
changed local x to 5
>>> print 'x is still',x
x is still 10
Global statement
    Global statements are defined using the global keyword. It is impossible to assign a value to a variable defined outside a function without the 'global' statement.
Example
>>> def fun():
...         global x
...         print 'x is',x
...         x=5
...         print 'changed global x to',x
Output
>>> x=10
>>> fun()
x is 10
changed local x to 5
>>> print 'Value of x is :',x
Value of x is : 5
Default Argument values
     This type of arguments are used to assign default values to the parameters.
Example
>>> def name(message,num=1):
... print message*num
Output
>>> name('Alice')
Alice
>>> name('Alice',6)
AliceAliceAliceAliceAliceAlice
    An important thing is that, default values are assigned only to the parameters which are at the end of the parameter list. That is name(message,num=5) is valid, but name(message=5,num) is not valid.
Keyword Arguments
     In some situations, functions have many parameters, but we want to only specify the values of some of them. In such situation we assign values to this parameters by naming them, this is called keyword arguments. We use the names instead of position to specify the arguments to functions.
Example
>>> def fun(x,y=2,z=10):
...       print 'x is:',x,' y is:',y,' z is:',z
Output
>>> fun(3,7)
x is: 3 y is: 7 z is: 10
>>> fun(25,z=24)
x is: 25 y is: 2 z is: 24
>>> fun(z=50,x=100)
x is: 100 y is: 2 z is: 50
    Two advantages of using the Keyword arguments are: (1) We dont worry about the order of the arguments. (2) We can give values to only those parameters that we want.
    In this example first, the parameter x gets the value 3, y gets the value 7 and the parameter z uses the default value 10. In second case, parameter x gets the value 25, y uses the default value and z gets the value 24. In third case x gets the value 100, y gets the default value and z gets the value 50. Here order of arguments are not important. We can pass argument values to parameters in any order by using the name of parameters.
Return Statement
Return statement used to return from the function. Optionally we can return value from a function by using the return statement.
Example
>>> def largest(a,b):
...         if a>b:
...             return a
...         else:
...             return b
Output
>>> print largest(67,45)
67
Every function implicitly contain an return statement. If you not return any value, that return statement return a none value.
DocStrings
Python has a feature called Documentation String, which is usually referred to as docstrings. It helps to document the program better and makes it more easy to understand.
Example
>>> def max(x,y):
...         '''Prints the maximum of two numbers.
...         the two values must be integers.'''
...         x=int(x)
...         y=int(y)
...         if(x>y):
...             print x,'is maximum'
...         else:
...             print y,'is maximum'
Output
>>> max(5,8)
8 is maximum
>>> print max.__doc__
Prints the maximum of two numbers.
the two values must be integers.
     docstring is the first logical line of a function. Note that docstring also applied to modules and classes. Here the first line start with a capital letter and ends with a dot. Then the second line is blank followed by any detailed explanation starting from the third line.
     These are the basic concepts of function in python. Detailed description of function are described in the following posts.