Skip to content

Instantly share code, notes, and snippets.

@retronym
Created October 24, 2010 13:44
Show Gist options
  • Select an option

  • Save retronym/643539 to your computer and use it in GitHub Desktop.

Select an option

Save retronym/643539 to your computer and use it in GitHub Desktop.
lazy-option-partial-func.scala
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