Erlang Deliciousness

Tuesday, April 3, 2007

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.

Tags:

| Permalink

2 Comments »

  1. I also love the anagrams algorithm:

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

    Comment by Giovanni Intini — Tuesday, 03 April 2007 @ 15:32:15

  2. 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 :D

    Comment by Anoop Sankar — Saturday, 19 May 2007 @ 09:29:06

RSS feed for comments on this post. TrackBack URI

Leave a comment