dpiz9879
2015-03-10 19:41 阅读 36

Go walk树的Erlang翻译

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanbi2760 duanbi2760 2015-03-10 20:14

    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.
    
    点赞 评论 复制链接分享

相关推荐