Search code examples
erlangerlang-shell

Erlang lists:keyfind/3 not working as expected


What's wrong with the following code fragment?

> A = [{X, 1} || X <- lists:seq(1,5)].
> lists:keyfind({3,1}, 1, A).
false

Why is the function returning false? It should ideally return {3,1}.


Solution

  • lists:keyfind/3 searches a list of tuples by comparing the Nth value of each tuple against the given value. Your code is searching for a tuple whose first element is {3, 1}, which doesn't exist in your list. To search for tuples whose first element is 3, you can do lists:keyfind(3, 1, A).:

    1> A = [{X, 1} || X <- lists:seq(1,5)].
    [{1,1},{2,1},{3,1},{4,1},{5,1}]
    2> lists:keyfind({3,1}, 1, A).
    false
    3> lists:keyfind(3, 1, A).
    {3,1}
    

    If you want to find an exact value, you can use lists:member/2 to check if it exists:

    4> lists:member({3,1}, A).
    true