Compose partial functions

前端 未结 2 778
清酒与你
清酒与你 2021-02-05 12:47

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 func

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 13:47

    Here's a shorter way than the linked question, taken from this thread:

      val f = Map("a" -> 1, "b" -> 2)                 
    
      val g = Map(1 -> 'c', 3 -> 'd')                 
    
      def andThenPartial[A, B, C](pf1: PartialFunction[A, B], pf2: PartialFunction[B, C]): PartialFunction[A, C] = {
        Function.unlift(pf1.lift(_) flatMap pf2.lift)
      }                                               
    
      val h = andThenPartial(f, g)            //> h  : PartialFunction[String,Char]
    
      h.isDefinedAt("a")                      //> res2: Boolean = true
      h.isDefinedAt("b")                      //> res3: Boolean = false
      h.lift("a")                             //> res4: Option[Char] = Some(c)
      h.lift("b")                             //> res5: Option[Char] = None
    

    This can also be wrapped up as an implicit class, of course:

      implicit class ComposePartial[A, B](pf: PartialFunction[A, B]) {
        def andThenPartial[C](that: PartialFunction[B, C]): PartialFunction[A, C] =
          Function.unlift(pf.lift(_) flatMap that.lift)
      }
    
      val h2 = f andThenPartial g         //> h2  : PartialFunction[String,Char]
    
      h2.isDefinedAt("a")                 //> res6: Boolean = true
      h2.isDefinedAt("b")                 //> res7: Boolean = false
      h2.lift("a")                        //> res8: Option[Char] = Some(c)
      h2.lift("b")                        //> res9: Option[Char] = None
    

提交回复
热议问题