functional programming - With a Scala Either, how do you stop at the first error, but gets the already computed values -
for example, let have function
def foo(): either[string, int] = ???
i want call function 3 times. if values right
, want sum. if have 1 left
, want error , sum of previous right
values (~ stop computation @ point).
the way found :
list(foo, foo, foo).foldleft((none, 0)) { case ((some(err), sum), _) => (some(err), sum) case ((none, sum), fn) => fn() match { case left(err) => (some(err), sum) case right(x) => (none, sum + x) } }
is there generic functional programming feature (with cats or scalaz example) that?
using stream.span
:
val (ints, rest) = stream.continually(foo()).take(3).span(_.isright) val sum = ints.map(_.right.get).sum val error = rest.headoption
Comments
Post a Comment