Pattern Matching in List Comprehension Generators as a Filter

Two doors with a red and white chevron pattern and a decorative iron bar across the center of each door

What can Elixir do for your digital product? Set up you to scale without mountains of tech debt, for one. Book a free consult to learn how we can put it to use for you.

After years of learning and using Elixir, I had always assumed that the pattern-matching in the for generator would produce a match error if it didn’t match.

It turns out that it just drops non-matching items.

For some examples, of when this may be useful:

Let’s assume you don’t care about failed results, you could do something like this

stream = Task.async_stream(items, &do_expensive_thing/1)

# Filters on only successful results.
for {:ok, success} <- Enum.to_list(stream) do
  do_something_with_result(success)
end

or this

file_contents =
  "my/directory/with/files"
  |> File.ls!()
  |> Enum.map(fn file ->
    File.read!(file) |> Jason.decode()
  end)

# Filters on file contents that were proper JSON.
for {:ok, decoded} <- file_contents do
  do_something_with_decoded_json(decoded)
end

Sources:

Newsletter

Stay in the Know

Get the latest news and insights on Elixir, Phoenix, machine learning, product strategy, and more—delivered straight to your inbox.

Narwin holding a press release sheet while opening the DockYard brand kit box