if I have a `List<A>` and a function `A -&gt...
# arrow
f
if I have a
List<A>
and a function
A -> Option<B>
, is there an operator, or series of operators, that would iterate over the list, applying the function, and return the first
Option<B>
that is a
Some<B>
, and if none do, returns
None
? Similar to a
findFirst
but runs a computation
j
There are multiple ways to do this: First the most basic one is:
filterMap(f).firstOption()
using
filterMap
from
FunctorFilter
and
firstOption
from
Foldable
. (If you do the same with
asSequence().filterMap(f).firstOption()
it'll also be lazy ^^). When this pr (https://github.com/arrow-kt/arrow/pull/1897) is merged you can also do
map(f).asum(Option.alternative(), ListK.foldable())
asum
basically tries every element and short-circuits on success (which is similar to
traverse
which short-circuits on failure). I'd suggest doing the
asSequence().filterMap(f).firstOption()
because it won't apply the function unnecessarily and because it is available now ^^.
🔝 1
f
Oh that’s great! thanks for the reply! I’ll try it out!