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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大