tags:

views:

1329

answers:

2

I saw this code in Erlang:

[X-$0 || X<-someFun()]

In that line I found the -$0 syntax very useful.

I read the code and estimated what it means, but I'm not quite sure: is it split all numbers?

I'd like to see the explanation or man page of that syntax but I can't find it. Can anyone show me the right page?

+10  A: 

What that code is doing is taking the output from someFun() (which needs to return a list), and for each element in the list it is assigning the element's value to the variable X and then subtracting the ASCII value of the character 0 from that value. The resulting list is then the value of that whole expression.

What it's doing, in practice (and I've written this code dozens of times myself), is assuming that someFun/0 is a function that returns a string with just digits in it, and then converting that string into a list of the digits. So, if someFun() returned "12345", the result of this list comprehension is [1, 2, 3, 4, 5].

If you're familiar with the concept of a map function (as in, MapReduce), then this should be sounding pretty familiar by now.

This wikibooks page looks like a good introduction to Erlang list comprehensions:

http://en.wikibooks.org/wiki/Erlang_Programming/List_Comprehensions

Joe Armstrong's book "Programming Erlang", from the Pragmatic Bookshelf, (http://pragprog.com/titles/jaerlang/programming-erlang) also covers list comprehensions really well (along with everything else Erlang related). Excellent book, highly recommended, etc.

womble
+1  A: 

The normal documentation page for list comprehensions is in the Erlang Reference Manual Section 6.22 and in Programming Examples Section 3.

Both of these are on the main documentation page (click on the Erlang Programming Folder on the left hand menu bar).

The Erlang documentation is fab - it's just its layout is a tad shonky...

Gordon Guthrie