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]

Friday 23 March 2012

SSH Tunnels

Suppose you have a server called fred.bloggs.ac.uk at your institution and you have written some nice server which is listening on port 9999 and some nasty man suddenly in the middle of your course blocks port 9999. What do you do?

Luckily you can SSH onto fred.blogs.ac.uk

(1) Run you server as normal on fred.blogs.ac.uk listening on port 9999.

(2)  then type: ssh -L4950:fred.bloggs.ac.uk:9999 fred.bloggs.ac.uk

(3) finally point your clients at your machine port 4950 and off you go!

Simple!

Saturday 3 March 2012

Ubuntu vs Mint

I can't really tell the difference. They are the same. Ubuntu seems initially not good because Unity is the default window manager. Just do apt-get install gnome and then before login in go to settings and choose 'Classic'

In fact, I'd go for Ubuntu because it has much more online information about it.

Friday 15 January 2010