Skip to content

Instantly share code, notes, and snippets.

@PavelZaytsev
Created December 2, 2018 10:30
Show Gist options
  • Save PavelZaytsev/0c3281f797e565548219f32b78fc8230 to your computer and use it in GitHub Desktop.
Save PavelZaytsev/0c3281f797e565548219f32b78fc8230 to your computer and use it in GitHub Desktop.
sealed trait Option[+A]
case class Some[+A](get: A) extends Option[A]
case object None extends Option[Nothing]
sealed trait EitherError[Exception, +A]
case class RecoverableError(e: Exception)
extends EitherError[Exception, Nothing]
case class Result[+A](value: A) extends EitherError[Exception, A]
object Option {
def >==>[A, B, C](a: A => Option[B], b: B => Option[C]): A => Option[C] = {
input: A =>
val optionB: Option[B] = a(input)
flatMap(optionB)(b)
}
def map[A, B](o: Option[A])(f: A => B): Option[B] = o match {
case Some(value) => Some(f(value))
case None => None
}
def flatMap[A, B](o: Option[A])(f: A => Option[B]): Option[B] = o match {
case Some(value) => f(value)
case None => None
}
def pure[A](a: A): Option[A] = Some(a)
}
object EitherError {
def >==>[A, B, C](
a: A => EitherError[Exception, B],
b: B => EitherError[Exception, C]): A => EitherError[Exception, C] = {
input: A =>
val eitherB: EitherError[Exception, B] = a(input)
flatMap(eitherB)(b)
}
def map[A, B](e: EitherError[Exception, A])(
f: A => B): EitherError[Exception, B] = e match {
case Result(value) => Result(f(value))
case re @ RecoverableError(_) => re
}
def flatMap[A, B](e: A)(
f: A => EitherError[Exception, B]): EitherError[Exception, B] = e match {
case Result(value) => f(value)
case re @ RecoverableError(_) => re
}
def pure[A](e: A): EitherError[Exception, A] = Result(e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment