Echo with a new line from fun ()

I recently tried to deal with Erlang, but I was a little confused by this ...

Problem

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

Attempt

My function attempt:

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

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

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

... and then send him a message ...

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

... It seems that I do not get a new line character after writing and before the message returns.

Question

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

Thank you in advance

+4
source share
1 answer

Your problem is atomicity. After printing the first line, the "main thread" receives the planned one and prints the result Pid ! Msg Pid ! Msg , i.e. Msg .

io: fwrite can accept arguments exactly like printf in C:

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

Source: https://habr.com/ru/post/1385514/


All Articles