Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation with a sequence of by-name parameters in Scala?

Tags:

scala

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

like image 249
Sebastien Lorber Avatar asked Dec 04 '25 18:12

Sebastien Lorber


1 Answers

You can indeed use a Seq[() => Either[Error, Item]] to defer the computation at collection creation time. So for example

val doSomething1: () => Either[Error, Item] = () => { println(1); Right(1) }
val doSomething2: () => Either[Error, Item] = () => { println(2); Right(2) }
val doSomething3: () => Either[Error, Item] = () => { println(3); Left("error") }
val doSomething4: () => Either[Error, Item] = () => { println(4); Right(3) }
val doSomething5: () => Either[Error, Item] = () => { println(5); Left("second error") }
val l = Seq(doSomething1, doSomething2, doSomething3, doSomething4, doSomething5)

(Items are Ints in the example and Errors are Strings)

Then you can process them lazily stopping at first failure using the following recursive function:

def processUntilFailure(l: Seq[() => Either[Error, Item]]): Either[Error, Seq[Item]] = {
  l.headOption.map(_.apply() match {
    case Left(error) => Left(error)
    case Right(item)  => processUntilFailure(l.tail).right.map(_ :+ item)
  }).getOrElse(Right(Nil))
}

So now when I run processUntilFailure(l)

scala> processUntilFailure(l)
1
2
3
res1: Either[Error,Seq[Item]] = Left(error)

If you wanted to generate a Either[Seq[String], Seq[Int]] (processing all the operations). You could do it with a little change:

def processAll(l: Seq[() => Either[Error, Item]]): Either[Seq[Error], Seq[Item]] = {
  l.headOption.map(_.apply() match {
    case Left(error) => processAll(l.tail) match {
      case Right(_) => Left(Seq(error))
      case Left(previousErrors) => Left(previousErrors :+ error)
    }
    case Right(item)  => processAll(l.tail).right.map(_ :+ item)
  }).getOrElse(Right(Nil))
}

The only change as you can see is the Left case in the pattern match. Running this one:

scala> processAll(l)
1
2
3
4
5
res0: Either[Seq[Error],Seq[Item]] = Left(List(second error, error))

processAll can be replaced with a generic foldLeft on l

val zero: Either[Seq[Error], Seq[Item]] = Right(Seq[Item]())
l.foldLeft(zero) { (errorsOrItems: Either[Seq[Error], Seq[Item]], computation: () => Either[String, Int]) =>
  computation.apply().fold(
    { (error: String) => Left(errorsOrItems.left.toOption.map(_ :+ error).getOrElse(Seq(error))) },
    { (int: Int) => errorsOrItems.right.map(_ :+ int) })
}

processUntilFailure can 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.

like image 65
Ratan Sebastian Avatar answered Dec 07 '25 07:12

Ratan Sebastian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!