Sunday 22 September 2013

I Just wrote a fast concurrent permutation function in Erlang

   -module(perms).
   -export([perms/2,addAll/2,start/1,printAll/0,f/2]).


   start(L) ->    
        Pid1=spawn(perms,printAll,[]),
        perms(L,Pid1).

   perms([],Pid) -> Pid![];
   perms([H|T],Pid) ->
        Pid1 = spawn(perms,f,[H,Pid]),
        perms(T,Pid1).
       
   f(H,Pid) ->    receive
            L -> g(H,L,Pid),
            f(H,Pid)
        end.       

   g(H,[],Pid) ->    Pid![H];

   g(X,[H|T],Pid) ->
        Pid![X|[H|T]],       
        Pid1=spawn(perms,addAll,[H,Pid]),
        g(X,T,Pid1).
       
   addAll(H,Pid) ->
        receive
            L ->Pid![H|L],
            addAll(H,Pid)       
        end.
       
   printAll()->
        receive
            L -> io:format("~w.~n",[L]),
            printAll()                   
        end.   

To run it try for example, perms:start([1,2,3,4,5,6,7]).

Wednesday 18 September 2013

I'm Learning Erlang

Here is my first Erlang Code:

-module(factorial).
-export([fact/1,sum/1,flatten/1,flatten1/1,flatten2/1]).

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

sum([]) -> 0;
sum([H|T])  -> H + sum(T).

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

flatten([]) -> [];
flatten([X|L]) when is_list(X)  -> append(flatten(X),flatten(L));
flatten([X|L])           -> [X|flatten(L)].   

%comment

%alternatively with if
flatten1([]) -> [];
flatten1([X|L]) -> if is_list(X)  -> append(flatten1(X),flatten(L));
              true   ->[X|flatten1(L)]
           end.  


%or with ++


flatten2([]) -> [];
flatten2([X|L]) when is_list(X)  -> flatten2(X) ++ flatten2(L);
flatten2([X|L])           -> [X|flatten2(L)].   




To run it

(1) first install Erlang with apt-get install erlang
(2) Then type erl at the command line
(3) Then compile it with c(factorial).
(4) Then try out some expressions e.g.
factorial:flatten2([[1,2],3,[4,5,6]]).
It will say:
[1,2,3,4,5,6]