erlangerlang-shell

lists:any true in false cases?


I run the following anonymous function and variables in the interpreter, and get wrongly so a true statement, but why is that, and what do I need to change:

Lst = [1,2,3].
Y = 52.
lists:any(fun(Y) -> lists:member(Y, Lst) end, Lst).

Solution

  • This is because the Y in the argument list of the fun shadows the outer definition of Y. It therefore checks if any list element is a member of the list, which is always true.

    You don't actually need lists:any here; you can call lists:member directly, without lists:any:

    > lists:member(Y, Lst).
    false
    

    The equivalent using lists:any would be:

    > lists:any(fun(X) -> X =:= Y end, Lst).             
    false
    

    Here, the argument is X, so we can access Y from outside the fun.