Why Erlang variable is unused?

十年热恋 提交于 2019-12-20 17:28:46

问题


Why does compiling this code:

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

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

report:

./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

And return wrong result: full Self.


回答1:


This is because variables occurring on the LHS of generators, X and Y here, are always new unbound variables local to the comprehension. This means that they are not the same variables as the X and Y in the head of triples and, therefore, there is no implicit equality test. This similar to funs where all variables occurring in the head of a fun are alse new variables local to the fun.

This is different from most of the rest of erlang, which is why the compiler not only warns that the X and Y in the head are not used but also that the X and Y in the comprehension shadow the other variables. They are also unused anywhere in the comprehension.

An easy way to get what you want is:

[ Result || Result = {X1,Y1,_} <- Self, X =:= X1, Y =:= Y1 ]


来源:https://stackoverflow.com/questions/1277867/why-erlang-variable-is-unused

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!