St.Antario -4 years ago 102
Scala Question

# Combine 2 partial functions

I have two partial functions returning unit (

`f1`
,
`f2`
). For instance, something like that:

``````val f1 = {
case s: arg => //do some
//etc... lots of cases
}

val f2 = {
case s: anotherArg => //do some
//lots of cases
}
``````

Is there a concise way to compose this to partial functions the way as that if

``````f(x) = {f1(x); f2(x)} iff f1.isDefinedAt(x) && f2.isDefinedAt(x)
f(x) = f1(x); iff f1.isDefinedAt(x) && !f2.isDefinedAt(x)
f(x) = f2(x); iff !f1.isDefinedAt(x) && f2.isDefinedAt(x)
``````

# orElse

``````f1 orElse f2
``````

Scala REPL

``````scala> val f: PartialFunction[Int, Int] = { case 1 => 1 }
f: PartialFunction[Int,Int] = <function1>

scala> val g: PartialFunction[Int, Int] = { case 2 => 2 }
g: PartialFunction[Int,Int] = <function1>

scala> val h = f orElse g
h: PartialFunction[Int,Int] = <function1>

scala> h(1)
res3: Int = 1

scala> h(2)
res4: Int = 2

scala> h.isDefinedAt(1)
res6: Boolean = true

scala> h.isDefinedAt(2)
res7: Boolean = true
``````

Both both functions to execute on common cases

# Using List of partial functions and foldLeft

Scala REPL

``````scala> val f: PartialFunction[Int, Int] = { case 1 => 1 case 3 => 3}
f: PartialFunction[Int,Int] = <function1>

scala> val g: PartialFunction[Int, Int] = { case 2 => 2  case 3 => 3}
g: PartialFunction[Int,Int] = <function1>

scala> val h = f orElse g
h: PartialFunction[Int,Int] = <function1>

scala> h(3)
res10: Int = 3

scala> h(3)
res11: Int = 3

scala> val h = List(f, g)
h: List[PartialFunction[Int,Int]] = List(<function1>, <function1>)

scala> def i(arg: Int) = h.foldLeft(0){(result, f) => if (f.isDefinedAt(arg)) result + f(arg) else result }
i: (arg: Int)Int

scala> i(3)
res12: Int = 6
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download