Tuesday, 5 July 2005

Functional programming in Python

I was dismayed to read about Guido wanting to remove lambda, reduce, map and filter from Python. Although Guido's point about list comprehensions (and indeed the shocking complexity of some "fold" style transformations) is sensible, I'm not convinced that reducing the nice mixture of functional / imperative / OO is the best way to go. I mean, people can write spaghetti code in any paradigm, that doesn't mean we should abolish nested loops or multiple inheritance, right?

It was disappointing to read that Guido things that arithmetic is where functional style stuff is used most (well, I'm paraphrasing a bit there). While this might be true for reduce (or not, I dunno), it certainly isn't true for the rest. String munging and simple parsing is a good example of where the functional style can be very elegant. For example, the following takes a type declaration of the form "int, int, int -> int" and returns a list of the constituent types (e.g. ['int', 'int', 'int', 'int']). Of course, you could do this with loops, or regexps, or a lexer generator (!), or whatever, but the functional style is just so damn nice to look at:

def parse_types(s):
import string
def rem_arrow(s):
return filter((lambda x: not(x == "->")), s)
def strip_commas(s):
return map((lambda x: rstrip(x, ',')), s)
return rem_arrow(strip_commas(string.split(s)))

Note, that I could have used a bunch more lambdas here, but explicit def's are more readable. Whilst Guido complains about over-use of lambda, this is a matter of good style.

Bob tells me that someone once said (Abramsky?) that good language design should make anything semantically undesirable syntactically impossible. Here, Guido is trying to make bad stylistic decisions syntactically impossible, which I guess is the opposite view to Perls many ways to do everything and all of them unreadable. I have some sympathy with Guido's view, but can't help feeling pretty heartbroken about the idea of losing lambda.

Oh, and I'm not (nor have ever been) a Lisp or Scheme hacker.

No comments:

Post a Comment