Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active August 29, 2015 13:59
Show Gist options
  • Save davidallsopp/10513480 to your computer and use it in GitHub Desktop.
Save davidallsopp/10513480 to your computer and use it in GitHub Desktop.
Composing partial functions such that isDefinedAt works end-to-end. Requires that the functions are pure. Adapted from https://groups.google.com/forum/#!topic/scala-user/fnw_367xTTw
val f = Map("a" -> 1, "b" -> 2) //> f : scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2)
val g = Map(1 -> 'c', 3 -> 'd') //> g : scala.collection.immutable.Map[Int,Char] = Map(1 -> c, 3 -> d)
//def pandThen[A, B, C](pf1: PartialFunction[A, B], pf2: PartialFunction[B, C]): PartialFunction[A, C] = {
// Function.unlift((a: A) => pf1.lift(a) flatMap pf2.lift)
//}
implicit class ComposePartial[B, C](pf: PartialFunction[B, C]) {
def andThenPartial[D](that: PartialFunction[C, D]): PartialFunction[B, D] =
Function.unlift(pf.lift(_) flatMap that.lift)
def composePartial[A](that: PartialFunction[A, B]): PartialFunction[A, C] =
Function.unlift(that.lift(_) flatMap pf.lift)
}
val h = f andThenPartial g //> h2 : PartialFunction[String,Char] = <function1>
h.isDefinedAt("a") //> res6: Boolean = true
h.isDefinedAt("b") //> res7: Boolean = false
h.lift("a") //> res8: Option[Char] = Some(c)
h.lift("b") //> res9: Option[Char] = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment