Created
October 24, 2010 13:44
-
-
Save retronym/643539 to your computer and use it in GitHub Desktop.
lazy-option-partial-func.scala
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
| trait LazyOption[+A] { | |
| def isDefined: Boolean | |
| def fold[AA >: A, B](ifSome: AA => B, ifNone: => B): B | |
| def orSome[AA >: A](a: => AA): AA = fold(identity[AA] _, a) | |
| // etc | |
| } | |
| object LazyOption { | |
| def some[A](a: => A): LazyOption[A] = new LazyOption[A] { | |
| lazy val a0 = a | |
| def isDefined = true | |
| def fold[AA >: A, B](ifSome: AA => B, ifNone: => B) = ifSome(a0) | |
| } | |
| def none[A]: LazyOption[A] = new LazyOption[A] { | |
| def isDefined = false | |
| def fold[AA >: A, B](ifSome: AA => B, ifNone: => B) = ifNone | |
| } | |
| } | |
| type PartialFunc[-A, +B] = (A => LazyOption[B]) | |
| object PartialFunc { | |
| import LazyOption._ | |
| def compose[A, B, BB >: B, C](pf1: PartialFunc[A, B], pf2: PartialFunc[BB, C]): PartialFunc[A, C] = (a: A) => pf1(a).fold(pf2, none) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment