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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看