Wednesday, December 24, 2008

Numerology in Erlang

After a long time, again with the same problem but using a different language. I have been watching the talks on Erlang - about its strength and stability. I thought why not give it a try.

This is the same numerology problem written in Erlang.


-module(numero).
-export([value/1,start/1]).

start(Args) -> value(lists:nth(1,Args)).

value(NAME) -> io:write(sum(0,lists:sum([val(A) || A <- NAME]))),io:nl(),halt().

sum(SUM,NUM) when NUM > 0 -> Q = NUM,
R = Q rem 10,
NEWQ = Q div 10,
sum(SUM + R,NEWQ);
sum(SUM,0) ->
if
SUM > 9 -> sum(0,SUM);
true -> SUM
end.


val(C) ->
if
(($A =:= C) or ($J =:= C) or ($I =:= C) or ($Y =:= C) or ($Q =:= C)) -> 1;
(($B =:= C) or ($K =:= C) or ($R =:= C)) -> 2;
(($S =:= C) or ($C =:= C) or ($L =:= C) or ($G =:= C)) -> 3;
(($T =:= C) or ($D =:= C) or ($M =:= C)) -> 4;
(($E =:= C) or ($N =:= C) or ($X =:= C) or ($H =:= C)) -> 5;
(($U =:= C) or ($V =:= C) or ($W =:= C)) -> 6;
(($O =:= C) or ($Z =:= C)) -> 7;
(($F =:= C) or ($P =:= C)) -> 8;
true -> 0
end.