I’d like to implement validation for a sequence of operations that all return Either[Error,Item]
It should be fail-fast (in my initial need), I mean, returning Either[Error,Seq[Item]].
If there is an error, it’s obvious i do not want the following operations to be performed.
But in the future i may want to collect all the errors instead of returning only the first one.
I know Scalaz can do the job but for now I quite don’t understand all parts of Scalaz and I’m pretty sure there’s a simpler way to do it without using Scalaz, but using by-name parameters for exemple.
Is there a way to store by-name parameters in a sequence?
So that i can create a sequence of by-name values that represent my operations?
I mean, some kind of type Seq[=> Either[Error,Item]]
Then I could do something like calling takeWhile or collectFirst or something somilar, without all the operations being performed before the creation of the sequence?
I would expect the operations to be performed only when iterating on the sequence.
Thanks
You can indeed use a
Seq[() => Either[Error, Item]]to defer the computation at collection creation time. So for example(
Items areInts in the example andErrors areStrings)Then you can process them lazily stopping at first failure using the following recursive function:
So now when I run
processUntilFailure(l)If you wanted to generate a
Either[Seq[String], Seq[Int]](processing all the operations). You could do it with a little change:The only change as you can see is the Left case in the pattern match. Running this one:
processAllcan be replaced with a genericfoldLeftonlprocessUntilFailurecan as well but not easily. Since aborting early from a fold is tricky. Here’s a good answer about other possible approaches when you find yourself needing to do that.