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?
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)
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?)
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.
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?
I forget about flat_map and it’s great for this task. It embodies the “map, but maybe only keep some”, like you say. So as the coder, I’m on alert as to what’s happening. Vis-a-vis reduce which is totally open-ended structure creation. And so its presence doesn’t give any kind of ‘hint’ to the reader.
Since this is a “good pattern” thread… shouldn’t the name of the function represent that it’s also doing something with errors rather than just filtering for oks?
I guess people hate typing out those pesky tuples but I like having to do it (and don’t super love options types) because it doesn’t ‘hide’ the underlying data structure and thus makes reading the code have less mental overhead.