Pages: [1]   Go Down
Print
Author Topic: esercizio  (Read 2433 times)
0 Members e 1 Utente non registrato stanno visualizzando questa discussione.
Franco Barbanera
Moderator
Forumista Eroico
*****
Offline Offline

Posts: 3.083



WWW
« on: 06-04-2018, 16:01:28 »

%factg g 0 = g 1

%factg g n = (g n)*(factg g (n-1))


-module(factg).
-export([fg/2,compute/3]).

fg(G,N) ->
       spawn(factg,compute,[G,N,self()]),
       receive
          Result -> Result
       end.


compute(G,N,PIDfather) ->
         if
           (N==0) -> PIDfather!G(1);
           true  ->  spawn(factg,compute,[G,N-1,self()]),
                            Res1 = G(N),
                            receive
                              Res2 -> PIDfather!(Res1 * Res2)
                            end
                  end.
 
% Exercise: modify the program in order the values
%           can be multiplied as soon as they are computed
                                             
Logged
Franco Barbanera
Moderator
Forumista Eroico
*****
Offline Offline

Posts: 3.083



WWW
« Reply #1 on: 09-04-2018, 17:00:14 »

Bozza proposta soluzione


Code:
fg(G,N) -> PidManager = spawn(factorial_functions,managerCalc,[1,N+1,self()]),

          [spawn(factorial_functions,computeSingleCalc,[G,M,PidManager]) || M<-lists:seq(0,N)],
           
           receive  FinalRes -> FinalRes end.


managerCalc(State,NumCompActs,PID) -> if
                                    (NumActs==0) -> PID!State,
                                     true        -> X = receive Ris -> Ris*State
                                                            end       
                                   end,
                                   managerCalc(X,NumCompActs-1).


computeSingleCalc(G,M,PidManager) ->   PidManager!G(M).

Logged
Pages: [1]   Go Up
Print
Jump to: