Saturday, April 2, 2011

Functional python programming in April Fools

This is not djangish stuff but still tooks me a while of hacking.

I wanted to make an April Fools Day joke on my dear students and mess up their names on student records.

All I had need to do is to export Google Spreadsheet as CSV, read first column with "surname firstname" format. Then split surnames from firstnames, sort the firstnames list and join them again.
Aaby Joe
Daby Ann
Zaby Ian
to
Aaby Ann
Daby Ian
Zaby Joe

So I make a simple python script:

import csv
reader = csv.reader(open('notes.csv', 'rb'), delimiter=',', quotechar='"')
i = 0
surnames=[]
firstnames=[]
for row in reader:
 if i > 2:
  surnames.append( row[0].decode('utf-8').split(' ')[0] )
  firstnames.append( row[0].decode('utf-8').split(' ')[1]  )
 i+=1
firstnames.sort()
newnames = map(lambda x: x[0] + ' ' +x[1], zip(surnames, firstnames))
print newnames

I looked at this and thought - what a long python code. This is so simple task, shouldn't be written in so sparse way. Also omitting the two first lines looks awful. This should be done with slicing.

After while of hacking I've end up with this:

import csv
print  map(lambda x: "%s %s" % (x[0], x[1]), reduce(lambda x, y: zip(x, sorted(y)), zip(* map(lambda x : x.split(' '), [row[0] for row in csv.reader(open('a.csv'))][3:]))))

But this became a typical one-liner that is completely unreadable after one week. I felt that I need to make some indentation to this code anyway to make it readable:

import csv
print  map ( lambda x: 
            "%s %s" % (x[0] , x[1]), 
          reduce ( 
            lambda x,y: 
               zip(x, sorted(y)), 
            zip (* map(
                  lambda x: 
                     x.split(' '),  
                  [row[0] for row in csv.reader(open('notes.csv'))][3:])
               ) 
         ) 
      )

So functional programming is fun, but the problem is you need to read code inside-out, not bottom-down and that is sometimes difficult. I am wondering if there will be someday a programming language that will support functional programing with bottom-down oriented syntax.

No comments:

Post a Comment