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.

2 responses

  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 😀

  2. I also love the anagrams algorithm:

    anag([]) -> [[]];
    anag([L]) -> [[H|T]] || H

Leave a Reply

Create a website or blog at