Digging into python: part 4 | Functional programming tools

When it comes to functional programming..

I guess all of you might know how to define a function in python. If not it's just simple, see the example below

>>>def add(a,b):
. . .    return a+b
>>>x,y=5,6
>>>print add(x,y)
11

It's just simple as you can see the above code. As python is a dynamically typed language we don't need to specify the return type. So this is how we write a function in python. Functional programming is a programming paradigm. It's your decision how to write code. But there are some cases where we must not use functional programming. When it comes to data privacy and security it is always best to go with Object oriented programming concept. In python there are certain functions like map(),reduce(),filter().

map()

This function takes at least two argument one the function to be called and the other the sequence of values to be passed as an argument to that function. If you have multiple parameters for a particular function then you should specify multiple sequences. For example

>>>def add(x,y):
. . .    return x+y
>>>seq=range(4)
>>>a=map(add,seq,seq)
>>>print a
0,2,4,6

below you can see the screen shot for more clarification


filter()

filter() is also similar to map(), we have to pass at least two arguments. filter() will also return a list of values where it is true for each item in the given sequence. For an example,
>>> seq=range(10)
>>> def check(x):
. . .       return x>4
. . .
>>> a=filter(check,seq)
>>> a
[5, 6, 7, 8, 9]

If we have more than one parameter to the function we have to pass that sequence also to filter().

Screen shot


reduce()

reduce always returns a single value. It takes 3 arguments, function, sequence, starting index. reduce() will hold the return value and pass it to the function on next iteration. At first time of execution value at the first index of sequence will be internally considered as the first argument. It can have at most 3 arguments. For example if we have to find the sum of 1 to 10 then,

>>> def sum(a,b):
. . .       return a+b
. . . 
>>> a=reduce(sum,range(1,11))
>>> a
55
screen shot for the code



So these are few techniques which are available in python and used for functional programming. Instead of using while loops or for loops, usage of these built-in functions will increase the performance of your code considerably.

Comments

Popular Posts