Friday, October 17, 2008

Python, Closures, map and filter

Closures are probably one of the greatest tools a dev can have in his toolbox. I used to use them a lot when I did assembly programming where they were called "macros". According to Martin Fowler they were called "Blocks" in Smalltalk. Ruby has them, Lisp is pretty much nothing but closures. They're freaking great. I mean really, really, really freaking great. If you don't use them you should learn how. Like now. Really. Unfortunately, if you're a Java programmer you're pretty much out of luck. I remember seeing a write up about somehow, kinda, sorta making closures work in Java but it seemed like a clusterfuck. But whatever. Just start using python (or maybe jython). They come with the box and they're drop dead easy to use. If you want some examples see this: click me

With closures map() and filter() become nectar of the gods. This is the magic combination:


With this combination all kinds of code can be squished down into near non-existance. I like to think of it as the neutron star of python: compacting code down to miniscule levels. It's not everyday that I come across a case that needs the neutron star pattern but when I do the day always seems a little brighter.

No comments: