Skip to content

Instantly share code, notes, and snippets.

@mergeconflict
Created June 13, 2014 21:45
Show Gist options
  • Save mergeconflict/db6d8c71af9977b6304e to your computer and use it in GitHub Desktop.
Save mergeconflict/db6d8c71af9977b6304e to your computer and use it in GitHub Desktop.
sealed trait Validation[+E, +A] {
def map[B](f: A => B): Validation[E, B]
def flatMap[EE >: E, B](f: A => Validation[EE, B]): Validation[EE, B]
def <*>[EE >: E, AA, B](aa: Validation[EE, AA])(implicit valueToFunction: A <:< (AA => B)): Validation[EE, B]
}
object Validation {
case class Success[+A](value: A) extends Validation[Nothing, A] {
def map[B](f: A => B): Validation[Nothing, B] =
Success(f(value))
def flatMap[EE, B](f: A => Validation[EE, B]): Validation[EE, B] =
f(value)
def <*>[EE, AA, B](aa: Validation[EE, AA])(implicit valueToFunction: A <:< (AA => B)): Validation[EE, B] =
aa map valueToFunction(value)
}
case class Failure[+E](errors: Seq[E]) extends Validation[E, Nothing] {
def map[B](f: Nothing => B): Validation[E, B] =
this
def flatMap[EE >: E, B](f: Nothing => Validation[EE, B]): Validation[EE, B] =
this
def <*>[EE >: E, AA, B](aa: Validation[EE, AA])(implicit valueToFunction: Nothing <:< (AA => B)): Validation[EE, B] =
aa match {
case Success(_) => this
case Failure(otherErrors) => Failure(errors ++ otherErrors)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment