Erlang Deliciousness

Witness: algorithm for finding factorial of a number.

fact(0) -> 1;
fact(N) -> N * fact(N - 1).

That of finding all permutations of a given string. "abc" -> ["abc", "acb", "bac", "bca", "cab", "cba"]:

perms([]) -> [[]];
perms(L) -> [[H|T] || H < - L, T <- perms(L--[H])].

That of getting the ‘next’ iteration of any string. next("a") -> "b". next("z") -> "aa". next("az") -> "ba":

next(L) -> lists:reverse(incr(lists:reverse(L))).
incr(L) when L =:= [] -> [$a];
incr([H|T]) when H =:= $z -> [$a|incr(T)];
incr([H|T]) -> [H + 1|T].

Deliciously, all these are also (with the addition of a module and export line) complete and valid erlang programs.

Stay tuned. I’m loving erlang.

Published by vishnugopal

Vishnu Gopal is an Anime fanatic, World of Warcraft player, SciFi nut, hopeless romantic & CTO at SV.CO.

Join the Conversation

2 Comments

Leave a Reply to Giovanni Intini Cancel reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

  1. oh this is cool.. just ran into Ruby, now erlang.. i seemed to have missed a lot of goodness. thanks for this though.. i have already played with this entire morning now!

    Disclaimer: not posted JUST to advertise my site 😀

    Like

%d bloggers like this: