Skip to content

Instantly share code, notes, and snippets.

@LeifW
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save LeifW/8380de5780b4af0cf7bd to your computer and use it in GitHub Desktop.

Select an option

Save LeifW/8380de5780b4af0cf7bd to your computer and use it in GitHub Desktop.
lift binary op to option (a la A: Semigroup => Option[A]: Monoid instance)
class Ring[A](o1: Option[A], f: (A, A) => A) {
def or(o2: Option[A]) = (o1, o2) match {
case (Some(x), Some(y)) => Some(f(x, y))
case (Some(_), None) => o1
case (None, _) => o2
}
def and(o2: Option[A]) = (o1, o2) match {
case (Some(x), Some(y)) => Some(f(x, y))
case _ => None
}
}
implicit class OptionApplyRing[A](o1: Option[A]) {
def apply(f: (A, A) => A) = new Ring(o1, f)
}
// Use like Option(4) apply(_ + _)or Option(5) == Some(9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment