Erlang: List Comprehensions

by javery on February 21, 2009

One of the most challenging things about learning a new language isn’t just learning how to do something, but more importantly learning the best way to do something. "Best" in this context is of course very subjective, but for me it not only means correctness but also readability, brevity, and following what is the normal convention for writing code in that language. Erlang has lots of ways to do things. I am working on a small solution where I am pulling messages back from Amazon SQS and processing them in Erlang. Here is a piece of code I initially wrote to handle looping through the list of messages and processing each of them:

process_messages(H|T, SQS) ->
process_message(H, SQS),
process_messages(T, SQS.
process_messages([], SQS) ->
ok.
process_message(Message, SQS) ->
%%process message here.

I was showing Mark this code and it struck him as strange, the process_messages function is just going through every item in the list and passing it to the process_message function, so a perfect case for map. So I rewrote the code using the lists:map function:

process_messages(List, SQS) ->
lists:map(fun(X) -> process_message(X, SQS) end, List).
process_message(Message, SQS) ->
%%process message here.

This is much nicer and reads better, I could even inline this code if I wanted to but I like the descriptiveness of having a function named process_messages. But, this can be even more descriptive using a list comprehension:

process_messages(List, SQS) ->
[process_message(X, SQS) || X <- List].
process_message(Message, SQS) ->
%%process message here.

An even simpler line of code and once you get comfortable reading list comprehensions it makes much more sense.

(found a nice Erlang Brush for Syntax Highlighter over here)

Comments on this entry are closed.

Previous post: Learning Erlang

Next post: 3 talks you should watch