Thursday, July 15, 2010

Functional Programming Terminologies:

1. Lambda:
Lambas help defining anonymous functions.
a = lamba x:x+3.
Here 'a' is a function variable. More importantly lamba is useful as anonymous function in Maps.

2. Map/Zip:
a) x = [ 1, 2, 3, 4, 5]
y = map (a,x) or map (lambda a : a + 3, x )
=> y = [ 4, 5, 6, 7, 8]

z = map (a, x, y) // map gives longest list length as the final/result list length
=> z = [ (4, 7), (5, 8), (6, 9) , (7, 10), (8, 11) ]
b = [ 1, 2]
z = map (a, x, b)
=> z = [ (4, 4), (5,5), (6, None), (7,None), (8,None)]
z = zip(a,x,b) // zip gives shortest list length as the final/result list length
=> z = [ (4,4) (5,5)]

3. Reduce
c = reduce(lamba x,y : x + y, a)
=> c = (((4 + 5) + 6) + 7) +8
=> c= 30

4. Filter:
c= filter (lambda x : x < 7, a)
=> c = [4, 5, 6]

5. List Comprehension:
Some of the above can also be done through list comprehension
c = [ i for i in a if i < 7 ]
c = [ 3 * i for i in a ]

No comments: