本文介绍了组成部分函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个PartialFunctions fg.它们没有副作用,执行起来很快.将它们组合为另一个分函数h的最佳方法是h.isDefinedAt(x) iff f.isDefinedAt(x) && g.isDefinedAt(f(x))?

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 thath.isDefinedAt(x) iff f.isDefinedAt(x) && g.isDefinedAt(f(x))?

如果h是返回Option的函数而不是部分函数,​​也可以.

It's also OK if h is a function returning an Option rather than a partial function.

对于f andThen g不能满足我的要求,我感到很失望:

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)

推荐答案

与链接的问题相比,这是一种更简短的方法,该问题取自此线程:

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

这篇关于组成部分函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:27