obfuscation
obfuscation

Reputation: 1043

Echo with new line from fun()

I've recently been trying to get to grips with Erlang, but am slightly confused by this...

Problem

I am trying to write a function object in the shell, which receives any message and echoes it back to the shell followed by a new line.

Attempt

My attempt at the function is:

Echo = fun() -> receive Any -> io:fwrite(Any), io:fwrite("~n") end end.

However, if I spawn a new process for this...

someNode@someHost 2> Pid = spawn(Echo).
<0,76,0>

...and then send it a message...

someNode@someHost 3> Pid ! "Hello".
Hello"Hello"

...I don't seem to get a new line character after the write, and before the message return.

Question

Is there something wrong with my approach, that stops this (very simple) example working as expected?

Thanks in advance

Upvotes: 4

Views: 762

Answers (1)

Kijewski
Kijewski

Reputation: 26043

Your problem is atomicity. After printing the first line, the "main thread" gets scheduled and prints the result of Pid ! Msg, i.e. Msg.

io:fwrite can take arguments just like printf in C:

Echo = fun() ->
    receive
        Any ->
            io:fwrite("~p~n", [Any])
    end
end

Upvotes: 4

Related Questions