Functional Programming 101: Lists and Closures
Join the DZone community and get the full member experience.Join For Free
lists and list comprehensions
the primitive we’re going to look at today is called a list comprehension . a list comprehension is similar to how we’re used to specifying sets in mathematics. if i wanted to a define as the set of all integers between 1 and 999 which are divisible by 3, i’d write:
see how similar this to the python code that uses a list comprehension to generate the same set.
x = range(1, 1000)
a = [ x for x in x if x % 3 == 0 ]
the reduce function
the reduce builtin function takes as arguments a function and a list (any sequence actually, if you want to be pedantic) and applies the function to the first two elements of the list, it then calls the function with the result of the first call and the third element, and so on.
that was confusing, so lets take an example.
def add(x,y): return x+y
print reduce(add, [1, 2, 3, 4, 5]
the reduce call in this program translates to a set of operations like this:
r1 = add(1, 2)
r2 = add(r1, 3)
r3 = add(r2, 4)
r4 = ad(r3, 5)
you can think of reduce as applying a binary operator recursively on a vector to produce a scalar. the interesting thing about reduce is that in the case of an associative operator, you can easily parallelize the operation.
example 1: problem 1 from project euler
find the sum of all the multiples of 3 or 5 below 1000.
the problem is trivial to solve imperatively, but our goal is to write this using as many functional constructs as possible.
instead of solving it for the specific case of integers between 1 and 1000, lets generalize the problem and solve for the arbitrary range .
def sum35multiple(a, b):
l = range(a, b)
c = lambda n: n%3 == 0 or n%5 == 0
s = [ x for x in l if c(x) ]
return reduce(lambda x,y:x+y, s)
note the trick we play in lines 3 and 5. line 3 creates a local variable that holds a reference to an anonymous function and line 5 is the place where it is invoked. combined with closures, this can be used to implement some powerful idioms. we’ll see one example of that when we get around to currying .
a closure is a somewhat more complicated concept and it will probably take more than one blog entry to get through. so, in this post, we’re going to dive in and use the damn thing before trying to understand it works.
again our target is a problem from project euler - problem 6.
the sum of the squares of the first ten natural numbers is,1² + 2² + … + 10² = 385
the square of the sum of the first ten natural numbers is,(1 + 2 + … + 10)² = 55² = 3025
hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
this problem is also rather trivial to solve both imperatively as well as mathematically. but for the purposes of this post, we’re going to take a hybrid semi-computational solution. we need to get through a little math before we get down to code.
our goal is to find:
i’ll skip the details here, but it is easy to show that:
here is straightforward translation of this equation into python code.
sn = n*(n+1)/2
i = range(1, n+1)
d = map(lambda x,y: (sn - x)*y, i, i)
return reduce(lambda x,y: x+y, d)
i’ve introduced a new built-in function in this code, the
function. the map function takes a variable number of arguments, the
first of which is always a function, and the remaining all sequences.
it iterates over each sequence “in-step” and returns a new sequence
that is generated by applying the function on each element of the input
again, this is the kind of thing that is best explained with an example.
def print_add(x, y):
print "adding", x, y
print map (print_add, [1, 2, 3], [4, 5, 6])
running this snippet produces the output:
adding 1 4
adding 2 5
adding 3 6
[5, 7, 9]
with that explanation, it should be clear that the function call to map in the function d is simply to calculate each term of the first summation in the equation for d(n).
i guess you’re wondering how is all this related to a closure. in fact, i’ve sneaked a closure into the function d(n).
look at line 4 again, i’m using the local variable sn inside of the anonymous function. notice how this is fundamentally different from a function that you could create in a c-like language. the function created by the lambda is not even completely defined until line 2 in the function d(n) calculates sn. conceptually, we’re creating a different function to pass to map during each invocation of d(n). one of the reasons why people claim that functional languages afford large gains in productivity and elegance of expression is this ability to “close state” and create functions at runtime.
there’s a bit more to this business of passing functions around that i want to cover, but i hope i’ve whetted your appetite enough for now. until the next post, tata, bye-bye and let me know in the comments how you’re liking/disliking this.
Published at DZone with permission of Pramod Subramanyan, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.