List comprehension kicks ass 4

Posted by Aaron Feng Sat, 29 Sep 2007 02:50:00 GMT

Recently I'm on an Erlang high, so I have tried to play around with it as much as I can. It's very common for any application to create a new list based on an existing list. For example in C# you would do something like the following:

public List<string> QualifiedUserNames(List<User> users) {
  List<string> names = new List<string>();
  foreach(User user in users) {
    if(user.Age >= 30) {
      names.Add(user.Name);
    }
  }
  return names;
}

Equivalent code in Erlang:

QualifiedUserNames(Users) -> [Name || {user,{name,Name},{age, Age}} <- Users, Age >= 30]

The Erlang function uses list comprehension to do all the dirty work. It loops through every item in the Users list, and extracts only user "type" which matches the pattern {user,{name,Name},{age,Age}}. This is done because Erlang is a dynamic language, and the list doesn't have to contain heterogeneous items. Age >= 30 is a predicate that checks if the user should be added to the newly created list and if so, the Name is added.

Pretty cool, right? I think so. This capability is one of the many reasons why Erlang program is usually shorter than programs written in other languages. Well back to programming in Erlang some more.

Comments

Leave a response

  1. Todd Mon, 01 Oct 2007 17:06:52 GMT

    So shorter and more cryptic = better? I am not a fan of these mathematical type of syntax. Write any J lately?

    BTW - are you trying to write some apps for your phone? Why Erlang?

  2. Aaron Feng Tue, 02 Oct 2007 00:17:51 GMT

    I don't think cryptic is the right word.  Cryptic means one chose to implement code in an unintuitive manner in favorite of clever code.  List comprehension is not "clever" code, it's a way of life in Erlang.  It looks nothing like C# or Java because it's not supposed to.  Once there is an understanding of Erlang syntax, one will find it very concise.

    I'm not trying to write an application for my phone.  Erlang was invented for the telecomunication industry and it is not a language for cell phones.  It can solve general everyday problems.  Erlang was created with concurrency in mind and it is designed to be extremely fault tolerant. It is also great for high speed distributed applications.

  3. ashton Wed, 09 Jan 2008 21:27:39 GMT

    Your blog is very interesting. I use python at work, and noticed that list comprehension is much nicer than Erlang :P QualifiendNames = [user.name for user in Users if user.age >= 30]

  4. Aaron Feng Thu, 10 Jan 2008 03:05:39 GMT

    Ashton,

    I'm glad you enjoy my blog. Python's syntax for list comprehension is really nice.

Comments