Created
October 27, 2014 07:21
-
-
Save igstan/d2ad0d7ef5bc8777ebce to your computer and use it in GitHub Desktop.
This file contains 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
object NumericOption { | |
implicit def numericOption[A](implicit N: Numeric[A]): Numeric[Option[A]] = | |
new Numeric[Option[A]] { | |
def fromInt(x: Int): Option[A] = Option(N.fromInt(x)) | |
def negate(x: Option[A]): Option[A] = x.map(N.negate(_)) | |
// Not sure whether these should return zero or throw an error... | |
def toDouble(x: Option[A]): Double = x.map(N.toDouble(_)).getOrElse(0) | |
def toFloat(x: Option[A]): Float = x.map(N.toFloat(_)).getOrElse(0) | |
def toInt(x: Option[A]): Int = x.map(N.toInt(_)).getOrElse(0) | |
def toLong(x: Option[A]): Long = x.map(N.toLong(_)).getOrElse(0) | |
def minus(x: Option[A], y: Option[A]): Option[A] = for (a <- x; b <- y) yield N.minus(a, b) | |
def plus(x: Option[A], y: Option[A]): Option[A] = for (a <- x; b <- y) yield N.plus(a, b) | |
def times(x: Option[A], y: Option[A]): Option[A] = for (a <- x; b <- y) yield N.times(a, b) | |
def compare(x: Option[A], y: Option[A]): Int = { | |
(x, y) match { | |
case (Some(x), Some(y)) => N.compare(x, y) | |
case (Some(_), None) => 1 | |
case (None, Some(_)) => -1 | |
case (None, None) => 0 | |
} | |
} | |
} | |
def main(args: Array[String]): Unit = { | |
println(List[Option[Double]](Some(2.5), Some(3.5)).sum) // Some(6.0) | |
println(List[Option[Double]](Some(2.5), None).sum) // None | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment