Question

I'm doing a simple calculator for practice. This piece of code sends a number. However when I try to send a number X for example, it sends XX. This is what it looks like in console:

(pz@Molly)3> znamenka:send(0, prva_znamenka).
I'm about to send: 00
(pz@Molly)4>

This is the relevant piece of code:

send(X, Name) ->
    if 
        X =:= 0 ->
            Name!X;
        X =:= 1 ->
            Name!X;
        X =:= 2 ->
            Name!X;
        X =:= 3 ->
            Name!X;
        X =:= 4 ->
            Name!X;
        X =:= 5 ->
            Name!X;
        X =:= 6 ->
            Name!X;
        X =:= 7 ->
            Name!X;
        X =:= 8 ->
            Name!X;
        X =:= 9 ->
            Name!X;
        X =:= stop ->
            Name!X;
        true ->
            io:format("You didn't enter a number or stop.")
    end.


loop() ->
    receive
        stop ->
            exit({myExit});
        X ->
            io:format("I'm about to send: ~w", [X]),
            {rjesenje, rjesenje@Molly}!{self(), X},
            loop()
    end.
Was it helpful?

Solution

You are mixing 2 things. First the program prints the string with the io:format/2 function. As there is no new line at the end of the string, the cursor in the shell stays at the same place. Then the function send(X,Name) returns its value, that is the result of the if statement, so the message itself: 0 and add a new line before printing the prompt.

The 2 things are independent so it is possible that you get:

0I'm about to send: 0
(pz@Molly)4>

or:

0
I'm about to send: 0(pz@Molly)4>

I am not sure of the order.

If you comment the io:format lite, you will see a single 0 remaining, or if you add a new line to the send function like

end,
ok.

the second 0 will be replaced by ok.

OTHER TIPS

io:format("I'm about to send: ~w~n", [X]),

You will find the difference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top