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: