Patterns of Deconstruction
One of my favorite features of Haskell is its parameter patterns (yes, it\’s in ML, but I\’m not really the ML guy). They\’re a nice way to break down structures automatically, and to avoid doing conditionals explicitly. In an imperative language, you might have:
There. Does that mix enough programming styles into one code snippet? Looks kind of like Python, but you definitely can\’t do that pointer manipulation in Python. Yeah, I\’d say that\’s nasty enough. In Haskell, the same code would look like:
phew that was a bit clearer. But notice the tricky bit? It looks like I defined the function twice … the first one says \”if you pass me an empty array, I\’ll just return 0\” and the second says, \”give me an array and I\’ll automatically separate the first element for you to play with.\” You can take this even farther, doing things like
(x:y:z:rest) to get the first three elements to play with, or
(_:xs) to just throw away the first element.
This stuff is cool. The first time I wrote some Haskell code, it just changed the way I thought about things. So what\’s the problem? The problem is Lisp. Lisp doesn\’t do this … at least, not so well.
If you\’re writing a macro in lisp, you can do the deconstruction:
What does that for me? Well, the macro takes a 2-element list, the first of which is of arbitrary length (giving us the first element separate from the rest), the second is another 2-element list (throwing away the first). That\’s pretty heavily condensed code there. But, what if we want to do that outside of a macro? It\’s a bit less pretty.
Sure, it only adds one line, but still … why not just use it by default? (That\’s not rhetorical.)
The real problem, however, is the lack of patterns in the definition. I don\’t get the Haskell code from above, I get this:
definitely not as clean as the Haskell. Ces\’t la vie, I suppose.
This whining is mostly insincere — it\’s like an investor comparing stocks and mutual funds while some homeless guy is sitting next to him writing C++
^W^Wcounting his change.