Erlang & Single Assignment: You’re Doing It Wrong
Posted: July 28th, 2008 | Author: kevin | Filed under: Erlang | View CommentsPatrick Logan’s latest missive highlighting the complaints some people have about Erlang’s single-assignment semantics reminds me of something I’ve been wanting to say for a while:
If you are chronically bumping into the limitations of single-assignment then you’re doing it
wrong .
Off the top of my head, here are the two reasons I can think of why people don’t like single-assignment semantics (SAS for short):
- Looping over a collection of values – If you’re running afoul of SAS then you’re looping iteratively not functionally. You should investigate list comprehensions, recursive functions combined with pattern matching, or
map,fold,zip, orzipwithin thelistsmodule. If you really need plain old for-loop style iteration,lists:foreach/2should do nicely but in a functional style. - Reusing variables in the same function – Quit it. Really. Erlang is trying to tell you your function is either too long or doing too many things.
This isn’t to say that you’ll never bump into SAS. I run into it mostly when I’m writing code which makes heavy use of records and qlc although I daresay with a bit of thought and factoring I could remove those instances as well. Cobbler’s shoes and all that.
Rather than bring your favorite language’s paradigm to Erlang (Ruby, Python, Java, etc) try working with Erlang’s grain. The style of programming these techniques encourage, namely reducing side-effects and function complexity, are beneficial no matter what language you’re using.