Fletcher Moore
Fletcher Moore

Reputation: 13804

Cleaner way to iterate over tuples in elixir

I find myself writing a pattern something like this pretty often and I feel it is not ideal:

Enum.filter(my_list, fn e -> 
   case e do 
     {:ok, x} -> true
     {:error, y} -> false 
   end 
end)
|> Enum.map(fn e -> {:ok, something} = e; something end)

Where my_list is created by some function that returns {:ok, x} or {:error, y}

I do this when I want to ignore the errors.

Have any alternatives for me?

Upvotes: 1

Views: 2933

Answers (1)

Dogbert
Dogbert

Reputation: 222188

You should use for with the pattern {:ok, term} for this. for automatically ignores all values in the enumerable which doesn't match the pattern, which facilitates this elegant solution:

iex(1)> my_list = [{:ok, 1}, {:error, 2}, {:ok, 3}, {:ok, 4}, {:error, 5}]
[ok: 1, error: 2, ok: 3, ok: 4, error: 5]
iex(2)> for {:ok, term} <- my_list, do: term
[1, 3, 4]

Upvotes: 10

Related Questions