【问题标题】:What's the relationship between PartialFunction and Function1PartialFunction和Function1有什么关系
【发布时间】:2017-09-04 11:04:39
【问题描述】:

我正在学习Scala,从scala doc中找到PartialFunctionFunction1的定义,如下图:

trait PartialFunction[-A, +B] extends (A) ⇒ B
trait Function1[-T1, +R] extends AnyRef

Q1) 我的第一个问题是:(A) => B 的类型是什么?

而且,我知道我们可以通过 lift 方法将 PartialFunction 变成普通函数。

但是 Q2)ParitialFunctionFunction1 之间的关系是什么?

如果某个函数参数的类型是Function1,我们可以传递一个匹配的PartitionFunction给它,如下所示:

scala> val process = (f: Function1[String, Int]) => f("1024")
process: (String => Int) => Int = <function1>

scala> val pattern = "([0-9]+)".r
pattern: scala.util.matching.Regex = ([0-9]+)

scala> val str2int: PartialFunction[String, Int] = {
     | case pattern(num) => num.toInt
     | }
str2int: PartialFunction[String,Int] = <function1>

scala> accept(str2int)
res67: Int = 1024

谢谢!

【问题讨论】:

    标签: scala


    【解决方案1】:

    A ⇒ BFunction1[A, B] 的语法糖。同样,(A1, A2) ⇒ R实际上是Function2[A1, A2, R]等,一直到22(完全任意限制)。 PartialFunction 的定义是这样的

    trait PartialFunction[-A, +B] extends Function1[A, B]
    

    由于PartialFunction[A, B] 也是Function1[A, B],您可以将它传递给需要A ⇒ B 的东西。我们使用 而不是FunctionN 的唯一原因是美观:它看起来更好。事实上,由于 并不是真正的类型名称,我们不能这样说:

    type ApIntInt[T[_, _]] = T[Int, Int]
    // ApIntInt[⇒] // Error: ⇒ is not a type and was not expected here
    ApIntInt[Function1] // Fine: Function1 is a type, it has the right kind, so it works.
    // ApIntInt[Function1] = Function1[Int, Int] = Int ⇒ Int
    

    由于您是初学者,您将在很长一段时间内不会看到这种东西(更高的种类),但它就在那里,你可能有一天会遇到它。

    当您将PartialFunction 用作Function1 时,如果您传递未定义的值,它(可能)会引发异常,通常是MatchError(但不必是)。相比之下,如果您调用pf.lift,则会创建一个Function[In, Option[Out]],如果PartialFunction 在某个点定义,则返回Some(result),如果不是,则根据Scaladoc 返回None

    例如:

    lazy val factorial: PartialFunction[Int, Int] = {
      case num if num > 1 => num * factorial(num - 1)
      case 1 => 1
    }
    assert(!factorial.isDefinedAt(0))
    factorial.apply(0) // Using a PF as a Function1 on an undefined point breaks (here with MatchError)
    factorial.lift.apply(0) // This just returns None, because it checks isDefinedAt first 
    

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 2021-01-18
      • 1970-01-01
      • 2016-09-28
      • 2013-07-02
      • 2017-02-06
      • 2022-01-03
      • 2020-03-05
      • 2012-09-27
      相关资源
      最近更新 更多