dogweather

dogweather

Is this a good pattern for handling a list of {:ok|:error} results?

I’m parsing input, returning the successfully parsing items, and logging the parse errors. (In this app, this is the behavior I want: continue working with successful parses, and a log file with the errata.)

    processed_sections = map(raw_sections, &new_section/1)

    reduce(processed_sections, [], fn e, acc ->
      case e do
        {:error, msg} ->
          Logger.warn(msg)
          acc

        {:ok, section} ->
          acc ++ [section]
      end
    end)

Is there some more canonical way of working through the {:ok|:error} results?

Most Liked

Sorc96

Sorc96

I tend to prefer functions other than custom reduce, so in this case, I would probably do someting like this:

{successful, failed} = Enum.split_with(processed_sections, &match?({:ok, _}, &1))

Enum.each(failed, fn {:error, msg} -> Logger.warn(msg) end)

successful

Seriously though, we need a standardized higher level way to work with :ok and :error tuples.

100phlecs

100phlecs

You can get rid of the case statement with anonymous function pattern matching:

i.e.

[{1, 2}, {3}, {4, 5}]
|> Enum.reduce(0, fn
  {x, y}, acc -> acc + x + y
  {x}, acc -> acc + x
end)

or in your case

processed_sections = map(raw_sections, &new_section/1)

reduce(processed_sections, [], fn
  {:error, msg}, acc ->
    Logger.warn(msg)
    acc

  {:ok, section}, acc ->
    acc ++ [section]
end)
al2o3cr

al2o3cr

This can be golfed down even further by using Enum.flat_map to express the “map, but only keep some of them” idiom:

raw_sections
|> map(&new_section/1)
|> Enum.flat_map(fn
  {:ok, result} -> [result]
  {:error, msg} -> Logger.warn(msg); []
end)

Monad enthusiasts should be able to spot Result being transformed into Option there :stuck_out_tongue:

hst337

hst337

There are several ways to do this, but there is no “canonical” way.
Your solution has a problem with ++ operator, which makes this whole solution be O(n^2) complexity. I’d suggest prepending to the head and then reversing the result (or using Enum.flat_map)

awerment

awerment

Taking the opportunity for some bike shedding :slight_smile:… If you‘re not using the intermediate values, you could do it with some pipes:

raw_sections
|> map(&new_section/1)
|> reduce([], fn
  {:error, msg}, acc ->
    Logger.warn(msg)
    acc

  {:ok, section}, acc ->
    [section | acc]
end)
|> reverse()

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement