3

Find all occurrences of {1, _}; in other words, all first element values that are 1 from each tuple in the list.

Consider the following input:

[
  {1, 0},
  {2, 2},
  {1, 1},
  {11, 1},
  {1, 3},
  {1, 2},
  {13, 1}
]

Expected Output:

[{1,0}, {1,1}, {1,3}, {1,2}]

I tried Enum.find(tl(input), fn x -> elem(x, 0) == elem(hd(input), 0) end), but I realized that Enum.find/2 only returns the first and only one element that matches the criteria or function, which is: {1,1}.

My goal is to find all tuples that contain {1, _}, where the first element must be 1 and the second element can be any value.

lattejiu
  • 119
  • 8

1 Answers1

12

Here you can use a comprehension with pattern-matching:

result = for x = {1, _} <- list, do: x

Any x that doesn't match the pattern {1, _} will be filtered out.

See the documentation for for/1 for more information.

You could also use Enum.filter/2 together with the match?/2 macro to achieve the same result:

result = Enum.filter(list, fn x -> match?({1, _}, x) end)

Enum.find/2 is useful when you are looking for a single element, e.g. if you want to find the first entry matching your condition.

sabiwara
  • 2,775
  • 6
  • 11
  • 2
    `Enum.filter(list, &match?({1, _}, &1))` or `Enum.filter(list, fn {1, _} -> true; _ -> false end)` :) Actually, comprehensions rule, of course. – Aleksei Matiushkin Mar 20 '21 at 13:00