Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composing PartialFunctions with orElse when there is a wildcard case

Is it possible to orElse compose two PartialFunctions when the first function has case _ => wildcard pattern that matches anything thus in effect being a total function.

For example, given

val pf1: PartialFunction[Int, String] = {
  case 1 => "foo"
  case 2 => "bar"
  case _ => "wildcard"
}

val pf2: PartialFunction[Int, String] = {
  case 3 => "baz"
  case _ => "wildcard"
}

then, out-of-the-box

(pf1 orElse pf2)(3)

outputs wildcard. However, assuming we cannot modify pf1, can we compose with pf2 using some compfn such that we get in effect

{
  case 1 => "foo"
  case 2 => "bar"
  case 3 => "baz"
  case _ => "wildcard"
}

where (pf1 compfn pf2)(3) would output baz?

like image 509
Mario Galic Avatar asked Oct 27 '25 08:10

Mario Galic


1 Answers

You can turn pf1 into a true partial function by doing a second match to convert the "wildcard" result to a failed match.

val pf3: PartialFunction[Int, String] = (i: Int) => pf1(i) match {
  case s if s != "wildcard" => s
}

And then

(pf3 orElse pf2)(3)

If you want the precise syntax you showed then you need to use an implicit class:

implicit class addCompfn(f1: PartialFunction[Int, String]) {
  def compfn(f2: PartialFunction[Int, String]) = (i: Int) => f1(i) match {
    case s if s != "wildcard" => s
    case s => f2(i)
  }
}

And then

(pf1 compfn pf2)(3)
like image 91
Tim Avatar answered Oct 28 '25 22:10

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!