Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalaz Validation: aggregate errors or return any success

Tags:

scala

scalaz

How is it possible to implement with scalaz such behaviour:

"Fail1".failNel[Int] and "Fail2".failNel[Int] to Failure("Fail1", "Fail2")
"Fail1".failNel[Int] and 100.successNel[String] to Success(100)

My solution looks to complicated and I guess exists some other way to do it succint:

  def aggregateErrorsOrSuccess(v1: ValidationNEL[String, Int], 
                               v2: ValidationNEL[String, Int]) = {
    v2.fold(
      nl => (nl.fail[Int] |@| v1) {(i1, i2) => (/*actually should never happen*/)},
      res => res.successNel[String]
    )
  }

=====================

My second solution:

implicit def nel2list[T](nl: NonEmptyList[T]) = nl.head :: nl.tail;

implicit def ValidationNELPlus[X]: Plus[({type λ[α]=ValidationNEL[X, α]})#λ] = new      Plus[({type λ[α]=ValidationNEL[X, α]})#λ] {
def plus[A](a1: ValidationNEL[X, A], a2: => ValidationNEL[X, A]) = a1 match {
    case Success(_) => a1
    case Failure(f1) => a2 match {
      case Success(_) => a2
      case Failure(f2) => (f1 <::: f2).fail[A]
    }
  }
}

Use it like this:

val sum = v1 <+> v2
like image 665
Eugene Zhulenev Avatar asked Feb 08 '12 15:02

Eugene Zhulenev


1 Answers

Indeed, you can use >>*<< (emergency exit?) method defined in Validation which is close to your second solution. However it will also try to aggregate successes, you may want tweak that.

def >>*<<[EE >: E: Semigroup, AA >: A: Semigroup](x: Validation[EE, AA]): Validation[EE, AA] = (this, x) match {
  case (Success(a1), Success(a2)) => Success((a1: AA) ⊹ a2)
  case (Success(a1), Failure(_)) => Success(a1)
  case (Failure(_), Success(a2)) => Success(a2)
  case (Failure(e1), Failure(e2)) => Failure((e1: EE) ⊹ e2)
}
like image 72
Mark Jayxcela Avatar answered Oct 07 '22 03:10

Mark Jayxcela