So what’s with the fuss about functional programming?
Well to start of with its a lot of fun to write, and it forces you to look at problems in a different way compared to your normal imperative way of solving things.
Plus I think python is awesome.
Functional Programming Paradigm
What functional programming essentially means is that you program keeping you functions black boxes. There are essentially 2 rules which have to followed while programming functionally:
1.There are no variables which your functions access outside of there scope.
Map , Filter and lambda are your best friends.
Imagine you have a list of numbers between 1 and 100.
num_list = range(0,101)
Now you want to filter out all the even numbers from this list?
Normal Imperative code:
for i in num_list:
if i%2 == 0:
The above code prints out all the positive numbers. Now you could also write a list comprehension and do this, but that also would involve a for loop.
print filter(lambda x: x%2 ==0, num_list)
Apart from the fact the code itself is much smaller and much more expressive, it can inherently take advantage of the much core system since each function execution is so to say an independent operation this could very well be optimized to run in parallel much more easily compared to imperative code.
Filter out odd numbers
print filter(lambda x: x%2 !=0, num_list)
Imagine you have a list containing intergers , and have to convert it to string .
string_list = [‘some’, ‘random’, ‘words’, ‘in’, ‘the’, ‘list’]
Basic difference between map and filter(In a general usage)
map applies the function on the variable(or list) and gives you the output of the function
filter keywords filters out all the elements or member for which the function you have written returns true.
For detailed introduction on map and filter the visit http://www.python-course.eu/lambda.php.
The reduce keyword continuously applies a function to a particular list and returns a single value.
for example get the sum of all the values of a list
reduce(lambda x,y: x+y, num_list)
The above expression will give you the sum of all elements in the list.
Functional programming gives a whole different out look on how to look at your code, and you may end coming with a completely different solution to problem.
You either love it or hate it, but you cannot ignore it.