Thursday, August 07, 2008

Maybe a couple of months ago some blogger whose feed is aggregated at Planet Intertwingly (I don't remember who) wrote a post summarizing his complaints about Erlang. One complaint was about extracting a value from a tuple. Say you assign a tuple to some variable, as in

1> X = {a, 10}.
{a,10}
and you want the value of the second element of the tuple. How do you do that? Conventionally,
2> {_, Y} = X.
{a,10}
3> Y.
10
Now the variable Y has the value 10. (In Erlang, the underscore is the anonymous variable.) If a tuple has a large number of fields or contains nested tuples, such tuple-unpacking statements are unwieldy. And that's what the guy objected to. It's too verbose and easy to botch.

Fortunately, pattern matching provides a simple way to work around this. Define a function that matches the tuple (particularly the first atom)
4> ValueOf = fun({a, Value}) -> Value end.
#Fun
5> ValueOf(X).
10
If you define one function for each element in a tuple, you get accessor methods for the tuple and you don't have to continue writing long expressions with a lot of anonymous variables.

No comments: