在Erlang中计数(如何增加一个变量?) [英] Counting in Erlang (how do I increment a variable?)
问题描述
我已经弄清楚了Erlang风格的循环:尾随递归与函数,使所有的变量不变: %%做某事,一次80字节
loop(Line,File) - >循环(Line,File,0)。
循环(行,文件,计数) - >
do_something(Line,Count),
案例文件:read(File,80)
{ok,Line2} - >循环(Line2,File,Count + 1);
eof - >文件:关闭(文件);
{error,Reason} - > {error,Reason}
结束。
但是,在Erlang增加柜台的最佳方式是什么?在大多数编程语言中,您计算事物的方式是增加一个变量(即 count + = 1;
)。埃尔朗的变数并不相同,所以我们必须有创意。幸运的是,我们有选项...
我们可以使用我们的函数传递一个Counter变量,并用每个函数调用来增加它。我们可以使用流程字典存储计数,并且获取
和 put
来增加它。我们可以使用ETS,本地数据存储进程。我们可以使用一个计数过程(!!!):
循环(Count) - >
收到
{incr} - >
循环(Count + 1);
{report,To} - >
到! {count,Count},
loop(Count)
end。
incr(Counter) - >
柜台! {incr}。
get_count(Counter) - >
柜台! {report,self()},
接收
{count,Count} - >计数
结束。
我确定还有其他方法,具体取决于范围。在Erlang中增加变量是什么被认为是最佳实践?
不要使用过程字典。
您正在期待的正常循环(即 循环或
code>)通常在Erlang的递归函数中实现,所以如果你增加一个正常计数器,在函数调用中就会显示出来。
不要使用过程字典。
如果你错过了,我可以指出你不应该使用过程字典。
I've figured out the Erlang-style loops: tail-recursion with functions that take all the "variables that don't vary":
%% does something, 80 bytes at a time
loop(Line, File) -> loop(Line, File, 0).
loop(Line, File, Count) ->
do_something(Line, Count),
case file:read(File, 80) of
{ok, Line2} -> loop(Line2, File, Count + 1);
eof -> file:close(File);
{error, Reason} -> {error, Reason}
end.
But, what is the best way to increment a counter in Erlang? In most programming languages, the way you count things is by incrementing a variable (ie. count += 1;
). Erlang's variables don't vary, so we have to be creative. Fortunately, we have options...
We can pass a Counter variable with our functions, and increment it with each function call. We can use the process dictionary to store a count, and get
and put
to increment it. We can use ETS, the local data storage for processes. We can use a counter process (!!!):
loop(Count) ->
receive
{ incr } ->
loop(Count + 1);
{ report, To } ->
To ! { count, Count },
loop(Count)
end.
incr(Counter) ->
Counter ! { incr }.
get_count(Counter) ->
Counter ! { report, self() },
receive
{ count, Count } -> Count
end.
I'm sure there are other ways too, depending on the scope. What's considered "best practice" for incrementing a variable in Erlang?
Don't use the process dictionary.
The 'normal' loop that you are expecting (ie a for
loop or a do while
) is usually implemented in a recursive function in Erlang so if you are incrementing a 'normal' counter do it in the function calls like you show up top.
Don't use the process dictionary.
In case you missed, can I just point out that you should not use the process dictionary.
这篇关于在Erlang中计数(如何增加一个变量?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!