Skip to content

Instantly share code, notes, and snippets.

@justjoheinz
Created November 23, 2013 11:55
Show Gist options
  • Save justjoheinz/7613775 to your computer and use it in GitHub Desktop.
Save justjoheinz/7613775 to your computer and use it in GitHub Desktop.
Chaining Validations
class ChainedValidation[E,A](val x : A, val validationResult: ValidationNel[E,A]) {
def andThen(f: A => ValidationNel[E, A])(implicit s1: Semigroup[E]) : ChainedValidation[E,A] = {
// calculate new validation
val newResult = f(x)
validationResult match {
// (success & newResult) =>
case Success(_) =>
newResult match {
// (success & success => success
case Success(a) => new ChainedValidation[E,A](x, a.successNel[E])
// (success & failure => failure
case Failure(e) => new ChainedValidation(x, e.fail[A])
}
// (failure & newResult =>)
case Failure(e) =>
newResult match {
// (failure & success) => failure
case Success(a) => new ChainedValidation(x, validationResult)
// (failure & failure) => failure + failure
case Failure(eNew) =>
new ChainedValidation(x, (e append eNew).failure[A])
}
}
}
}
object ChainedValidation {
def apply[E,A](x: A, f: A => ValidationNel[E, A]) = new ChainedValidation[E,A](x, f(x))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment