dogweather

dogweather

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?

Showing Posts 1 to 10

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)
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()
dogweather

dogweather OP

I noticed how generic my code is, and thinking about moving this to a separate function like Haskell’s fromJust or catMaybes: Data.Maybe (Does Elixir have a similar library?)

So, e.g.,

catOks(processed_sections, &Logger.warn/1)
dogweather

dogweather OP

Yeah, that’s pretty good. And then I’d just refactor it by extracting the function:

raw_sections
|> map(&new_section/1)
|> catOks(&Logger.warn/1)

Does Elixir have a library with functions like catOks? (Searching…)

awerment

awerment

I‘m not aware of one in the standard lib, but you already have most of it :slight_smile:

def cat_oks(list, fun) do
  list
  |> reduce([], fn
    {:error, msg}, acc ->
      fun.(msg)
      acc

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

Using ’Enum.filter/2’ would save you the need to reverse, though:

def cat_oks(list, fun) do
  list
  |> filter(fn
    {:error, msg} ->
      fun.(msg)
      false

    {:ok, section} ->
      true
  end)
end

Edit: Ah, sorry, disregard the above, it would not unwrap the tuples.

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.

cloudytoday

cloudytoday

Does Elixir have a similar library?

Towel (or specifically its recentmost fork) has it IIRC. Alternatively, calling Gleam’s result module would do the same. I have a personal helpers lib (a couple of them) with a whole bunch of utilities like this, but it’s not in the state where it would make sense to publish it. Anyways it wouldn’t take one more than a day or two to come up with one.

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:

cloudytoday

cloudytoday

Options are not about binding/flatmapping lists, an Option type would need to be represented as something like {:some, a} | :nothing, or did I misunderstand what you meant?

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews