为什么Erlang变量未被使用?

r4g*_*4ge 20 erlang

为什么要编译这段代码:

triples( [], _,_,_)->
  [];

triples( Self, X, Y, none )->
  [ Result || Result = { X, Y, _} <- Self ].
Run Code Online (Sandbox Code Playgroud)

报告:

./simple_graph.erl:63: Warning: variable 'X' is unused
./simple_graph.erl:63: Warning: variable 'Y' is unused
./simple_graph.erl:64: Warning: variable 'X' is unused
./simple_graph.erl:64: Warning: variable 'X' shadowed in generate
./simple_graph.erl:64: Warning: variable 'Y' is unused
./simple_graph.erl:64: Warning: variable 'Y' shadowed in generate
Run Code Online (Sandbox Code Playgroud)

并返回错误的结果:完全自我.

rvi*_*ing 51

这是因为在生成器的LHS上发生的变量,这里的X和Y,始终是理解本地的新的未绑定变量.这意味着它们与三元组中的X和Y不是相同的变量,因此,没有隐式的相等性测试.这类似于乐趣,乐趣之中出现的所有变量都是乐趣所在的新变量.

这与erlang的其余大部分不同,这就是为什么编译器不仅警告头部中的X和Y不被使用,而且理解中的X和Y也会影响其他变量.它们在理解中的任何地方也未被使用.

获得您想要的简单方法是:

[ Result || Result = {X1,Y1,_} <- Self, X =:= X1, Y =:= Y1 ]
Run Code Online (Sandbox Code Playgroud)

  • 哇.这是一个难题! (5认同)