了解 Erlang 中的“_”变量

Understanding '_' variable in Erlang

这里是 Erlang 新手。我来自 Java 背景,我发现 Erlan 相当有趣。正在关注这本优秀的书 "Learn You some Erlang"。

这是书中给出的用于反转列表顺序的递归示例:

tail_reverse(L) -> tail_reverse(L,[]).

tail_reverse([],Acc) -> Acc;
tail_reverse([H|T],Acc) -> tail_reverse(T, [H|Acc]).

这按预期工作。但是,如果我将代码更改为:

tail_reverse(L) -> tail_reverse(L,[]).

tail_reverse([],_) -> [];
tail_reverse([H|T],Acc) -> tail_reverse(T, [H|Acc]).

现在总是 returns [] 无论传递的列表内容如何。所以似乎 tail_reverse([],_) -> []; 行是被调用的那一行。但是,我的理解是只有当第一个参数为空并且 _ 只是一个占位符时才应该调用它。

我在这里错过了什么?

这一行:

tail_reverse([], Acc) -> Acc

应该 return 累积参数 Acc 当处理的列表变空时。您将其替换为:

tail_reverse([], _) -> []

在相同的情况下执行(递归的底部),但忽略了之前完成的工作并且 returns 是空列表。

至于_这个变量,跟你的问题关系不大,但是在this的回答里有解释。

@bereal 的回答是正确的。但是,我将对“_ 变量如何在 Erlang 中工作”这一一般性问题提供我自己的答案。我最近写了一篇关于 _ 变量的博客 post:

The anonymous variable is denoted by a single underscore (_). The anonymous variable is used when a variable is required but the value needs to be ignored. The anonymous variable never actually has the value bound to it. Since the value is never bound it can be used multiple times in a pattern and each time it is allowed to match a different value. Example:

1> {_, _} = {foo, bar}.
{foo, bar}
2> _.
* 1: variable '_' is unbound 
4> {_, Second} = {foo, bar}.
{foo, bar}
5> _.
* 1: variable '_' is unbound 
6> Second.
bar

此处提供更多信息: http://stratus3d.com/blog/2014/11/05/everything-you-need-to-know-about-erlangs-magic-variable/