We started off the PyGTA meeting with brainstorming for fun projects that we could do in a "pure functional" manner. Lots of complex and involved things that we'd whip off in a few minutes. But first, just to be sure we were all on the same page, let's whip off a quicky...
- given a file
- output the file on stdout sorted by the 5th character of each line
- use as pure a functional form as possible, with no variable assignments
It is *amazing* how addicted to variables a Python programmer is. All of us could trivially write the code as something like this:
import sys print "".join( [ x for x in sorted( [(line[4:5],line) for line in open(sys.argv)] ) ] )
But sorted is just syntactic sugar for creating and sorting a list, we wanted something that didn't use any variables/state, and we wanted to implement the sort ourselves to see how to do it purely functionally. We eventually came up with something... but OMG it was a mess, iterating over the whole file N times (via itertools.tee) searching for the N+1th item. Worse, the implementation of itertools.tee would mean that it was just creating N copies of the lists in dequeues.
So I looked up the Haskel qsort algorithm when I got home... the Python equivalent looks something like this:
def qsort( seq ): try: n = iter(seq).next() except StopIteration, err: pass else: seqs = itertools.tee(seq) for i in qsort( x for x in seqs if x < n ): yield i yield n for i in qsort( x for x in seqs if x > n ): yield i
Note the presence of variable assignments... which is one of the things we were considering a disqualification for "pure" functional style. The Haskel version uses "lazy lists" for everything, so they don't have the itertools.tee() call, and the n variable is part of the matching-head "unpack".
Which suggests we were being *way* too rigorous in our functional purity to work within the Python context. Sprinkling a bit of functionalism here and there might be useful, but the utility of eliminating all variable assignments is... suspect. That said, it was a very fun exercise to work on as a brain teaser, you don't realize how addicted you are to variable assignments until you declare that you cannot use them.
Pingbacks are closed.