如何将一个部分功能转换为另一个功能



假设我有部分功能parf

val parf: PartialFunction[Int, String] = { case 0 => "!!!" }

现在我也有case class A(x: Int),我需要一个功能将PartialFunction[Int, String]转换为PartialFunction[A, String]

def foo(pf: PartialFunction[Int, String]): PartialFunction[A, String] = ???

例如,foo(parf)应返回{case A(0) => "!!!" }。您将如何编写功能foo

要维护正确的功能,您需要检查您要通过的参数是否定义了内部部分函数:

val parf: PartialFunction[Int, String] = { case 0 => "!!!" }
case class A(x: Int)
def foo(pf: PartialFunction[Int, String]): PartialFunction[A, String] = {
  case A(i) if pf.isDefinedAt(i) => pf(i)
}

如果您打算更大的规模进行操作,则可能需要将部分函数转换为提取器对象,因此可以与更好的语法直接使用模式匹配:

trait Extractor[A, B] {
  def unapply(a: A): Option[B]
}
object Extractor {
  implicit def partialFunctionAsExtractor[A, B](pf: PartialFunction[A, B]): Extractor[A, B] =
    new Extractor[A, B] {
      def unapply(a: A) = if (pf.isDefinedAt(a)) Some(pf(a)) else None
    }
}
def foo2(pf: Extractor[Int, String]): PartialFunction[A, String] = {
    case A(pf(str)) => str
}
foo2(parf) // implicit conversion magic

我看不出是什么让你感到困惑?您只需要从A中匹配Int,然后让PF表现出来。

scala> case class A(x: Int)
// defined class A
scala> val parf: PartialFunction[Int, String] = { case 0 => "!!!" }
// parf: PartialFunction[Int,String] = <function1>
scala> def foo(pf: PartialFunction[Int, String]): PartialFunction[A, String] = { 
     |   case A(x) if pf.isDefinedAt(x) => pf(x)
     | }   
// foo: (pf: PartialFunction[Int,String])PartialFunction[A,String]
scala> val parfA = foo(parf)
// parfA: PartialFunction[A,String] = <function1>
scala> parfA(A(0))
//res0: String = !!!
scala> parfA(A(1))
// scala.MatchError: A(1) (of class A)
//   at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:254)
//   at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:252)
//   at $anonfun$1.applyOrElse(<console>:11)
//   at $anonfun$1.applyOrElse(<console>:11)
//   at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:34)
//   at $anonfun$foo$1.applyOrElse(<console>:13)
//   at $anonfun$foo$1.applyOrElse(<console>:13)
//   at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:34)
//   ... 28 elided

@oleg pyzhcov已经提供了一个很好的解决方案。另一种方法是创建在A(0(定义的部分功能[a,int],并使用andThen使用parf链接它:

val parf: PartialFunction[Int, String] = { case 0 => "!!!" }
case class A(n: Int)
val bar: PartialFunction[A, Int] = { case a: A if a.n == 0 => a.n }
def foo(pf: PartialFunction[Int, String]): PartialFunction[A, String] =
  bar andThen pf
// foo: (pf: PartialFunction[Int,String])PartialFunction[A,String]
foo(parf)
// res1: PartialFunction[A,String] = <function1>

相关内容

  • 没有找到相关文章