2009-08-23T06:58:56
Dave Pawson.
link
Home
erlang
After a throwaway comment from @timbray an opportunity arose to get a copy of a new O'Reilly book, Erlang Programming. It's a very impressive book. Written by a couple of people who really know their stuff, from inside and over a long time by the sound of it. Anyway it is now starting to look a little dogeared on my desk, and I still haven't read past page 150! I keep going back and re-reading bits. Bit like DSSSL? Or almost any of James Clarks writing. Information dense is the expression I use, where the information content of small paras is high! These guys have the same habit. I need to keep re-reading to get the most out of the book. Anyway. I'm enjoying Erlang. It has some strange features. One is a lack of assignment statements.
They call it pattern matching. Seems Erlang isn't unique in doing this, Dimitre tells me Haskell has it too. It (mostly) has the same effect as assignment, but only in a fallback case. Given
[false, Varname1, 42, {struct1, atom}] = Varname2;
[] is an array, {} is a structure/tuple, lc names are 'atoms' and names starting with UC are variables, which aren't, if you see what I mean.
So that statement deconstructs the variable on the RHS, looking for a pattern which matches the shape of the LHS. I.e. an array containing an atom, a 'something', a value of 43 and a structure which must contain two atoms. The fallback happens when that match has occurred, and the pragmatic part says that Varname1 can now be bound to a value from whatever pattern matches its position on the RHS. If it was a struct, array, float or whatever, is now assigned to the variable. I think that's a really neat idea. Either the pattern match succeeds, or it fails. Period. Given two values, one RHS, one LHS, e.g. the 42 in the example, then the RHS must match it in value! Simple. If a variable on the LHS has been 'assigned' a value, then it too must match the value on the RHS.
Pattern matching is used in Erlang all over the place, not just in 'assignments' if that's correct usage of the terminology. It is in quite wide use and makes a lot of sense, or did to me, once I'd become used to the idea of what was happening. There are a few more quirks, but that main idea is the one that hit me right between the eyes!
Message passing is the other big twist in Erlang.
Keywords: erlang
Comments (View)Return to main index