Functional programming is awesome. But while I have learned to respect it: the syntax of Anonymous inner-classes, in Java, could use a stronger dose of brevity (actually if closure support ever comes to Java this may happen). Fortunately, Python already has some seriously cool functional programming capabilities. Functions can be created on the fly, passed around, assigned to variables, sent through flaming hoops: whatever you want. In language-design speak this means that functions are first-class objects. Take a look at this interesting snipplet, which I have lifted from the code-base of my UTransit application (from the previous post):# A list of methods for accessing schedules
methods = [(getSchedulesForToday, {'TripPeriod': 'Regular'}),
(lambda t, s: getSchedulesAfterTodayMidnight(s), {'TripPeriod': 'NextDay'}),
(getSchedulesForEarlyToday, {'TripPeriod': 'Early'})]
# For each schedule access method, we invoke it and then get all schedules from it
for query, annotation in [(m[0](startTime, getStationByShortName(startStation)), m[1]) for m in methods]:
for begin in query:
itinerary = computeItineraryFrom(begin, destinationStation)
if not itinerary == None:
itinerary.update({'StartStation': startStation, 'State': 'RouteFound'})
itinerary.update(annotation)
return itinerary
The idea here is that we have multiple methods for accessing scheduling information, which is a list of functions. The for loop iterates over each one invoking it by passing the start time and station to it, since the second function only needs the later of the two arguments, we wrap a lambda around it that serves as an adapter (alright Gang-of-Four Junkies, I am aware this is officially known as the Decorator pattern). Note, that the methods list actually contains 2-tuples (method and dictionary). The dictionaries are merged with the computed itinerary (which, of course, is also a dictiony). Why is the itinerary a dictionary? Well, it so happens the return value is passed into a Django template.

