为什么PartialFunction&lt ;: Scala中的Function? [英] Why is PartialFunction <: Function in Scala?

查看:144
本文介绍了为什么PartialFunction&lt ;: Scala中的Function?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,PartialFunction[A, B]类是从类型Function[A, B]派生的(请参见Scala参考,12.3.3).但是,这对我来说似乎是违反直觉的,因为Function(需要为所有A定义)比PartialFunction更为严格,而PartialFunction在某些地方可能是未定义的.

In Scala, the PartialFunction[A, B] class is derived from type Function[A, B] (see Scala Reference, 12.3.3). However, this seems counterintuitive to me, since a Function (which needs to be defined for all A) has more stringent requirements than a PartialFunction, which can be undefined at some places.

我遇到的问题是,当我有部分函数时,我不能使用Function来扩展部分函数.例如.我做不到:

The problem I've came accross was that when I have a partial function, I cannot use a Function to extend the partial function. Eg. I cannot do:

(pf orElse (_)=>"default")(x)

(希望语法至少在右边)

(Hope the syntax is at least remotely right)

为什么要对这种子类型进行相反的处理?有什么我被忽略的原因,例如Function类型是内置的吗?

Why is this subtyping done reversely? Are there any reasons that I've overlooked, like the fact that the Function types are built-in?

顺便说一句,如果Function1 :> Function0也很好,所以我在上面的示例中不需要伪参数:-)

BTW, it would be also nice if Function1 :> Function0 so I needn't have the dummy argument in the example above :-)

可以通过看两个例子来强调两种方法之间的区别.他们中的哪一个是正确的?

The difference between the two approaches can be emphasized by looking at two examples. Which of them is right?

一个:

val zeroOne : PartialFunction[Float, Float] = { case 0 => 1 }
val sinc = zeroOne orElse ((x) => sin(x)/x) // should this be a breach of promise?

两个:

def foo(f : (Int)=>Int) {
  print(f(1))
}
val bar = new PartialFunction[Int, Int] {
  def apply(x : Int) = x/2
  def isDefinedAt(x : Int) = x%2 == 0
}
foo(bar) // should this be a breach of promise?

推荐答案

由于在Scala中(与任何图灵完整语言一样),不能保证功能是总数.

Because in Scala (as in any Turing complete language) there is no guarantee that a Function is total.

val f = {x : Int => 1 / x}

该函数未定义为0.PartialFunction只是一个函数,它会告诉您未定义的位置.尽管如此,Scala仍然足够轻松地执行您想要的操作

That function is not defined at 0. A PartialFunction is just a Function that promises to tell you where it's not defined. Still, Scala makes it easy enough to do what you want

def func2Partial[A,R](f : A => R) : PartialFunction[A,R] = {case x => f(x)}

val pf : PartialFunction[Int, String] = {case 1 => "one"} 

val g = pf orElse func2Partial{_ : Int => "default"}

scala> g(1)
res0: String = one

scala> g(2)
res1: String = default

如果愿意,可以将func2Partial隐式设置.

If you prefer, you can make func2Partial implicit.

这篇关于为什么PartialFunction&lt ;: Scala中的Function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆