Functional programming is a programming paradym that works by reducing the program to set of functions that ideally only have inputs and outputs and don’t have any internal state that changes the outcomes.

The simplist function would look something like this:

def add(a,b):
	return a+b

How on earth would you be able to create complex programs using something as simple as this? In this article we will go over a few methods that are used in functional programming using Python as the language. Python is a language that allows both precedural, declarative, object-oriented, and functional styles.

Iter

The way I think about functional programming is through it’s application. The benefits of using a really simple form is that you can also pass lists instead of just variables.

a = [1,2,3]
b = [1,2,3]
add(a,b)
returns [1,2,3,1,2,3]

Quickly we see that this doesn’t have the desired effect. We need to modify the first function.

def add(a,b):
	c=[]
	it = iter(zip(a,b))
	for i in it:
		c.append(i[0]+i[1])
	return c

Now, this returns the desired effect of adding any length list and you will get the sum back. You can do really fun things like:

a = [1,2,3]
b = [3,5,6]
add(add(a,b),add(a,b))
[8, 14, 18]

map

map has the following form:

map(f, iter(a), iter(b), etc.) 

The power of this function is that it uses something that is very close to what you may see in functional programming. Where the first function is applied to the next items on the list.

[add 1 2 3] 

So let’s use our earlier version of add:

def add(a,b):
  return a+b

and now use map

a=[1,2,3]
b=[1,2,3]
map(add, iter(a),iter(b))
<map object at 0x104d9ae90>

You get back this map object, which is simply the rules the execute. Functional programming won’t give you the answer until you ask for the solution. They will just capture the rules to get the solution. This is very efficient and is quite common in functional programming. If we don’t need to calculate it we won’t do it. To get the answer we need to cast the answer to a list.

list(map(add,a,b))
[2, 4, 6]

leaving it here

As you can see, the first function we used is easy to debug. But, then we use iter or map and we can make this much more powerful than the original function.