Created
April 25, 2015 16:49
-
-
Save ceedubs/f29df9d30ddd4b4994da to your computer and use it in GitHub Desktop.
Type inference of curried vs uncurried fold on Option
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
object CurryInference { | |
implicit final class OptionOps[A](val oa: Option[A]) { | |
/** curried fold */ | |
def curriedFold[B](z: => B)(f: A => B): B = oa.fold(z)(f) | |
/** uncurried fold */ | |
def uncurriedFold[B](z: => B, f: A => B): B = oa.fold(z)(f) | |
} | |
val age: Option[Int] = Some(19) | |
/* | |
* error: type mismatch; | |
* found : scala.util.Right[Nothing,Int] | |
* required: scala.util.Left[String,Nothing] | |
* age.curriedFold(Left("age is required"))(i => if (i >= 0) Right(i) else Left(s"$i is not positive")) | |
* ^ | |
*/ | |
//age.curriedFold(Left("age is required"))(i => if (i >= 0) Right(i) else Left(s"$i is not positive")) | |
/* | |
* Compiles. Without currying, LUB is determined to be Either[String, Int] | |
* | |
* Technically the LUB probably also has Product with Serializable | |
*/ | |
age.uncurriedFold(Left("age is required"), i => if (i >= 0) Right(i) else Left(s"$i is not positive")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment