What python looks like naked [01/10/2007 14:35:29]
The old lython code offers some nice syntactic sugar, but underneath, it's still the same old imperative-style python. I started to wonder what it would be like to make python functional all the way down.
The answer is that it would be ugly... but in a hauntingly beautiful sort of way.
Below is a simple python program that I wrote in an imperative style, and then refactored into a single python expression (two expressions if you count the import statement):
The trick was to recreate each element of the python syntax as a function. I didn't duplicate every corner of the language - just enough to convert this one program, but I did try to hit all the major keywords, including assignment,
try ... except and the various looping constructs.
Essentially what I did here was create a python-like DSL in python.
You can download the source files here:
- disfunctional.py - the original, imperative code (not an exact match anymore)
- lambdaful.py - the above code (functional style)
- primitives.py the functional primitives (less than 100 lines of python)
The hardest part was implementing generators, and the result only covers very simple generators. It was the only language feature that required more than a simple function.
The for statement became something much more like ruby's each - it's a function that takes a series and another function. Python has a map function that works this way, but x_for allows the use of x_break and x_continue. (These, and x_yield were among the easiest to implement, since they just raise exceptions.)
Although this code is ugly, writing it gave me a feel for the real power of a language like lisp. I realized it would not be hard at all to add new language features, or to rewrite the language to suit my own needs. For example, it would be trivial to create a resumable try block, so that you could ignore certain exceptions. (In fact, that's exactly how the generators work.)
This idea is a long way from being usable for real code, but I think that with some more test cases, and a nice lisp-like syntax, this could be a very exciting language in which to work.
