noether icon indicating copy to clipboard operation
noether copied to clipboard

Implement some kind of "first matching" function in Either

Open sphaso opened this issue 5 years ago • 0 comments

Big picture: having a function that applies another function on each element until it results in an {:ok, a} and stops at that point.

Example: find the first format that matches a particular date. The "first matching" function iterates over the list of formats, applies Timex.parse and returns the first result matching an :ok pattern

Naive-ish implementation using the existing choose:

def first_matching(list, f) do
  Enum.reduce(list, {:error, nil}, fn el, acc ->
     Either.map(acc, fn _ -> Either.choose(el, f, & &1) end)
  end)
end

sphaso avatar Jan 31 '20 08:01 sphaso