I have two PartialFunctions f
and g
.
They have no side effects and are quick to execute.
What's the best way to compose them into another partial function h
such that
h.isDefinedAt(x)
iff f.isDefinedAt(x) && g.isDefinedAt(f(x))
?
It's also OK if h
is a function returning an Option
rather than a partial function.
I'm disappointed that f andThen g
does not do what I want:
scala> val f = Map("a"->1, "b"->2)
f: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2)
scala> val g = Map(1->'c', 3->'d')
g: scala.collection.immutable.Map[Int,Char] = Map(1 -> c, 3 -> d)
scala> (f andThen g).isDefinedAt("b")
res3: Boolean = true
scala> (f andThen g).lift("b")
java.util.NoSuchElementException: key not found: 2
at scala.collection.MapLike$class.default(MapLike.scala:228)