Last active
August 29, 2015 14:10
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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