Bula
Bula

Reputation: 2792

Erlang translation of Go walk trees

I am trying to implement the Walk function from here which is implemented in Go into erlang.

Here is the result:

-module(tree).
-export([walk/1,test/0]).


walk({Left, Value, Right}) ->
    spawn(tree,walk,[Left]),
    io:format(Value),
    spawn(tree,walk,[Right]);
walk({}) -> continue.



test() ->
B = {{}, alina, {}},
D = {{},vlad,{}},
C = {D, tea, {}},
A = {B,maria,C},
walk(A).

I'm not sure if this belongs to the code review section as I'm not sure that what I did is what I wanted. The code works as expected (in the sense that it does walk a tree) however I'm not sure if the design of the function is concurrent.

Upvotes: 1

Views: 116

Answers (1)

Stratus3D
Stratus3D

Reputation: 4906

The function is indeed concurrent, as you are spawning new processes to walk the subtrees.

You might want to alter tree:walk/1 so that it returns the atom ok in the case of a successful walk (I also switch out io:format/1 with erlang:display so that values are printed on separate lines):

walk({Left, Value, Right}) ->
    spawn(tree,walk,[Left]),
    erlang:display(Value),
    spawn(tree,walk,[Right]),
    ok;
walk({}) -> continue.

Here is a synchronous version of the same function. Instead of processes, we use recursion:

walk_sync({Left, Value, Right}) ->
    walk_sync(Left),
    erlang:display(Value),
    walk_sync(Right);
walk_sync({}) -> continue.

Upvotes: 1

Related Questions