英文:
Erlang translation of Go walk trees
问题
我正在尝试将Go语言中的Walk
函数(这里)实现为Erlang语言。
以下是翻译好的代码:
-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 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
得分: 1
该函数确实是并发的,因为你在生成新的进程来遍历子树。
你可能想要修改tree:walk/1
函数,以便在成功遍历时返回原子值ok
(我还将io:format/1
替换为erlang:display
,以便将值打印在单独的行上):
walk({Left, Value, Right}) ->
spawn(tree, walk, [Left]),
erlang:display(Value),
spawn(tree, walk, [Right]),
ok;
walk({}) -> continue.
这是相同函数的同步版本。我们使用递归而不是进程:
walk_sync({Left, Value, Right}) ->
walk_sync(Left),
erlang:display(Value),
walk_sync(Right);
walk_sync({}) -> continue.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论