Search code examples
scalafunctional-programmingpartialfunction

applying partial function on a tuple field, maintaining the tuple structure


I have a PartialFunction[String,String] and a Map[String,String]. I want to apply the partial functions on the map values and collect the entries for which it was applicaple. i.e. given:

val m = Map( "a"->"1", "b"->"2" )
val pf : PartialFunction[String,String] = {
  case "1" => "11"
}

I'd like to somehow combine _._2 with pfand be able to do this:

val composedPf : PartialFunction[(String,String),(String,String)] = /*someMagicalOperator(_._2,pf)*/
val collected : Map[String,String] = m.collect( composedPf ) 
// collected should be Map( "a"->"11" )

so far the best I got was this:

val composedPf = new PartialFunction[(String,String),(String,String)]{
        override def isDefinedAt(x: (String, String)): Boolean = pf.isDefinedAt(x._2)
        override def apply(v1: (String, String)): (String,String) = v1._1 -> pf(v1._2)
      }

is there a better way?


Solution

  • Here is the magical operator:

    val composedPf: PartialFunction[(String, String), (String, String)] = 
      {case (k, v) if pf.isDefinedAt(v) => (k, pf(v))}
    

    Another option, without creating a composed function, is this:

    m.filter(e => pf.isDefinedAt(e._2)).mapValues(pf)