Samuel .R.F
Samuel .R.F

Reputation: 27

Erlang, how to print every value in console?

I have a start() function which spawns a process and runs a method multiple times in that process, its a simple calculator, so each line which says: calculadora:contador({suma,1,1},Server) prints into the console the result (in this case 1).

The problem is when start is called it only prints the last line of start which is: calculadora:contador('exit',Server) which gives as a result (ok,bye).

So my question is how do print every single result with this start function?

-module(calculadora).

-export([contador/2, loop/0, start/0]).

loop() ->
    receive
        {Pid, {suma, N1, N2}} ->
            Pid ! N1 + N2,
            loop();
        {Pid, {resta, N1, N2}} ->
            Pid ! N1 - N2,
            loop();
        {Pid, {multiplicacion, N1, N2}} ->
            Pid ! N1 * N2,
            loop();
        {Pid, {division, N1, N2}} ->
            Pid ! N1 / N2,
            loop();
        {Pid, exit} ->
            Pid ! {"Bye"};
        {Pid, _} ->
            Pid ! {error, "wtf"},
            loop()
    end.

contador(X, Pid) ->
    Pid ! {self(), X},
    receive
        {error, E} ->
            {bad, E};
        {Cont} ->
            {ok, Cont};
        R ->
            {ok, R}
    after 10 ->
        {error, timeout}
    end.

start() ->
    Server = spawn(?MODULE, loop, []),
    calculadora:contador({suma, 1, 1}, Server),
    calculadora:contador({multiplicacion, 1, 1}, Server),
    calculadora:contador({division, 1, 1}, Server),
    calculadora:contador({resta, 1, 1}, Server),
    calculadora:contador(exit, Server).

Upvotes: 2

Views: 496

Answers (1)

legoscia
legoscia

Reputation: 41568

Use io:format, like this:

io:format("Result: ~p~n", [calculadora:contador({suma,1,1},Server)]),

Upvotes: 2

Related Questions