Erlang – elegant, but mind blowing :)

I’ve been playing around with Erlang for a while now. Interesting thing about Erlang is that the language is pretty small and very consistent, I guess it is typical for functional language 🙂 , but in a same time it takes a long time to start thinking in “Erlang way”. Everything is based on pattern matching – function signatures, case and if statements are all just pattern matching. Once you get a hold of it… it is a lot of fun and makes code pretty clean, short and readable.
Here is an example of function that parses ttl – 20s, 10m, 2h :

first we have an entry point:

parse(Ttl) -> parse_ttl(lists:reverse(Ttl)).

And here comes all the fun :

%% Private Functions.

parse_ttl([$s | Ttl]) -> list_to_integer(lists:reverse(Ttl));
parse_ttl([$S | Ttl]) -> parse_ttl([$s | Ttl]);

parse_ttl([$m | Ttl]) -> 60 * list_to_integer(lists:reverse(Ttl));
parse_ttl([$M | Ttl]) -> parse_ttl([$m | Ttl]);

parse_ttl([$h | Ttl]) -> 60* 60 * list_to_integer(lists:reverse(Ttl));
parse_ttl([$H | Ttl]) -> parse_ttl([$h | Ttl]);

parse_ttl(_) -> false.

Since strings in Erlang are just lists of integers, it is very common to apply list functions to strings. The [H | T] notation allows you to separate “head” and a “tail” of the list; in our case first symbol and the rest of the string. And since we have reversed our original string before applying our pattern … it is working pretty well 🙂


About Wondering Bear
39 years old male bear.

One Response to Erlang – elegant, but mind blowing :)

  1. Hehe, my version also uses pattern matching, but with tuples:

    ms({Count, Units}) -> ms(Count, Units);
    ms(MS) -> MS.

    ms(Count, milliseconds) -> Count;
    ms(Count, seconds) -> ms(Count, milliseconds) * 1000;
    ms(Count, minutes) -> ms(Count, seconds) * 60;
    ms(Count, hours) -> ms(Count, minutes) * 60;
    ms(Count, days) -> ms(Count, hours) * 24;
    ms(Count, weeks) -> ms(Count, days) * 7.

    I use it internally in functions with configurable timeouts. So one can use integers direct or tuples like {2, hours}. I love pattern matching.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: