Scala:这两个部分函数是等价的吗?

时间:2015-11-21 15:54:18

标签: scala

这两个部分功能是否相同?

val f0: PartialFunction[Int, String] = {
  case 10 => "ten"
  case n: Int => s"$n"
}

val f1 = new PartialFunction[Int, String] {
  override def isDefinedAt(x: Int): Boolean = true
  override def apply(v: Int): String = if (v == 10) "ten" else s"$v"
}

UPD

val pf = new PartialFunction[Int, String] {
  def isDefinedAt(x: Int) = x == 10
  def apply(v: Int) = if (isDefinedAt(v)) "ten" else "undefined"
}

def fun(n: Int)(pf: PartialFunction[Int, String]) = pf.apply(n)
println(fun(100)(pf))

现在真的是PF吗?

1 个答案:

答案 0 :(得分:0)

我认为你需要2个部分(值)函数来使用它设计的方式PartialFunction:一个用于值10,另一个用于另一个Int s:

val f0:PartialFunction[Int, String] = { case 10 => "ten" }
val fDef:PartialFunction[Int, String] = { case n => s"$n" }

以及如何应用它们:

val t1 = (9 to 11) collect f0
t1 shouldBe(Array("ten"))
val t2 = (9 to 11) map (f0 orElse fDef)
t2 shouldBe(Array("9", "ten", "11"))