2015-11-21 69 views
0

這兩個部分功能是否等同?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

它們肯定總會有相同的行爲,但可能在字節碼中表示不同,具體取決於所使用的scala編譯器的版本。你在問什麼?這些也不是嚴格的局部函數,因爲它們總是被定義的... – jazmit

+0

我沒有得到這個'因爲它們總是被定義的'。你什麼意思? – Finkelson

+0

我需要添加'def fun(n:Int)(pf:PartialFunction [Int,String]):String = pf.apply(n)'來製作f0和f1 PartialFunctions? – Finkelson

回答

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"))