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 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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信
  • ¥30 Python调用dll文件输出Nan重置dll状态
  • ¥15 浮动div的高度控制问题。
  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题
  • ¥15 pic16F877a单片机的外部触发中断程序仿真失效
  • ¥15 Matlab插值拟合差分微分规划图论