Pattern Matching Brilliance in Erlang

Thursday, April 10, 2008 - 10:06 AM
No Comment - Post a comment

I'm preparing a blog post on guards and pattern matching in Erlang as it pertains to XML parsing. Until that post is finalize and published, I do want to mention just for a moment how great I think pattern matching is in Erlang. To do so, I'm going illustrate a very simple function in Erlang. This sample code isn't meant to demonstrate concurrency and isn't the best search method by far as it is of order N. However, it is interesting to see what can be done with pattern matching.

Our scenario is that we have a list (similar to array in most languages) and a value. We want to determine if the value is contained in the list. The code is as follows*:

lookup(Value,[Value|_]) -> found;
lookup(Value,[_|Tail]) -> lookup(Value,Tail);
lookup(_,[]) -> not_found.


The call would simply be:


Found=lookup(Value,List).


Now to dissect what is happening. Our lookup function listed above is recognized as one function in Erlang. The function name is lookup and the arity is 2. Erlang determines which part of the resulting code is executing in this function depending on what values are passed into the function.


  1. When the lookup is being called with a search value of "Jeremy" and the head** of the list is "Jeremy", the first result is evaluated and found is returned.

  2. When the head** of the list isn't "Jeremy", but there are still elements in the list, the second result is evaluated and lookup is returned by calling it again with "Jeremy" being the value and the tail** of the list being passed in as the list.

  3. When the value is "Jeremy" but the list is empty, the atom not_found is returned.



To me this is very elegant. I absolutely love this way of thinking.

*This code is very similar to what is found in the book Progamming Erlang - Software for a Concurrent World by Joe Armstrong. I recommend this book to anyone wishing to learn more about Erlang.

**The syntax [Head|Tail] is an Erlang syntax to access the first element of a List represented in the variable Head while the remaining list is stored in Tail. If my list was ["Jeremy","Dave","Mike","Matt"] Head would be "Jeremy" and Tail would be ["Dave","Mike","Matt"]

 
This Post has No Comment Add your own!

Post a Comment