带有 isDefinedA 的 Scala PartialFunction 并应用不工作
Scala PartialFunction with isDefinedA and apply not working
我是 Scala 的新手,我正在尝试 PartialFunctions,这是测试功能的正确方法吗,因为一些教程遵循此方法工作,但对我不起作用?
代码:
object MyScalaApp extends App {
def try29{
val r = new PartialFunction[Int, Int]
{
def isDefinedAt(q: Int) = q < 0 // Applying isDefinedAt method
def apply(q: Int) = 12 * q // Applying apply method
}
val rr = new PartialFunction[Double, Double]
{
def isDefinedAt(q: Double) = {q < 0}
def apply(q: Double) = 12 * q
}
println(r(1))
println(r(2))
println(rr(-1))
println(rr(-2))
}
}
try29
}
输出:
12
24
-12.0
-24.0
为什么 apply
在第一个条件不匹配时接到电话?
当我写 def isDefinedAt(q: Int) = q != 0
它给出 println(r(0))
作为输出 0
根据 ScalaDocs page:
It is the responsibility of the caller to call isDefinedAt
before calling apply
...
让我们在自动调用 isDefinedAt()
的上下文中尝试您的 r()
偏函数。
val r = new PartialFunction[Int, Int] {
def isDefinedAt(q: Int) = q < 0
def apply(q: Int) = 12 * q
}
List(4,-3,22,-9,0).collect(r)
//res0: List[Int] = List(-36, -108)
似乎按预期工作。
这不完全是你问的,但我认为值得一提的是 applyOrElse
的存在。如果您以后打算编写如下代码:
if(r.isDefinedAt(1)) r(1) else 10
最好使用 applyOrElse
,如文档中所述:
Note that expression pf.applyOrElse(x, default)
is equivalent to
if(pf isDefinedAt x) pf(x) else default(x)
except that applyOrElse
method can be implemented more efficiently. For all partial function literals the compiler generates an applyOrElse implementation which avoids double evaluation of pattern matchers and guards. This makes applyOrElse the basis for the efficient implementation for many operations and scenarios.
我是 Scala 的新手,我正在尝试 PartialFunctions,这是测试功能的正确方法吗,因为一些教程遵循此方法工作,但对我不起作用?
代码:
object MyScalaApp extends App {
def try29{
val r = new PartialFunction[Int, Int]
{
def isDefinedAt(q: Int) = q < 0 // Applying isDefinedAt method
def apply(q: Int) = 12 * q // Applying apply method
}
val rr = new PartialFunction[Double, Double]
{
def isDefinedAt(q: Double) = {q < 0}
def apply(q: Double) = 12 * q
}
println(r(1))
println(r(2))
println(rr(-1))
println(rr(-2))
}
}
try29
}
输出:
12
24
-12.0
-24.0
为什么 apply
在第一个条件不匹配时接到电话?
当我写 def isDefinedAt(q: Int) = q != 0
它给出 println(r(0))
作为输出 0
根据 ScalaDocs page:
It is the responsibility of the caller to call
isDefinedAt
before callingapply
...
让我们在自动调用 isDefinedAt()
的上下文中尝试您的 r()
偏函数。
val r = new PartialFunction[Int, Int] {
def isDefinedAt(q: Int) = q < 0
def apply(q: Int) = 12 * q
}
List(4,-3,22,-9,0).collect(r)
//res0: List[Int] = List(-36, -108)
似乎按预期工作。
这不完全是你问的,但我认为值得一提的是 applyOrElse
的存在。如果您以后打算编写如下代码:
if(r.isDefinedAt(1)) r(1) else 10
最好使用 applyOrElse
,如文档中所述:
Note that expression
pf.applyOrElse(x, default)
is equivalent toif(pf isDefinedAt x) pf(x) else default(x)
except that
applyOrElse
method can be implemented more efficiently. For all partial function literals the compiler generates an applyOrElse implementation which avoids double evaluation of pattern matchers and guards. This makes applyOrElse the basis for the efficient implementation for many operations and scenarios.