[mancano i commenti, che vanno sempre inseriti]
[soluzione non testata]

-module(mapfun).
-export([map/2,compute/3]).



collectRes(IDs,ListIdRes,0) -> order(IDs,ListRes);

collectRes(IDs,ListIdRes,N) -> receive

                                  {ID,Res} -> collectRes(IDs,[{ID,Res}|ListIdRes],N-1)

                                   end.



order([],_)               -> [];

order([ID|IDs],ListIdRes) -> {R,L} = pickAndRestOf(ID,ListIdRes),
                             [R| order(IDs,L)].



pickAndRestof(ID,[{ID,Res}|Rest],Prev) -> {Res,lists:append(Prev,Rest)};

pickAndRestof(ID,[Pair|Rest],Prev) -> pickAndRestof(ID,Rest,list:append(Prev,[Pair])).




map(_,[]) -> [];

map(F,List) ->

         ComputingActors = [spawn(mapfun,compute,[F,X,self()]) || X <- List ], %Just for readability. We can directily put the list as argument of collectRes
         
         collectRes(ComputingActors,[],lists:lenght(List)).                             





compute(F,X,Collector) -> Res = F(X),
 
                          Collector!{self(),Res}.


