斯卡拉有一個內置FunctionN
性狀高達Function22
。有相應的PartialFunctionN
似乎很自然。那爲什麼scala沒有它?有沒有一個固有的原因,爲什麼它不包含在scala中?爲什麼scala沒有內置的PartialFunctionN?
很容易,我自己實現了接近PartialFunctionN
的東西。我們當然可以定義很明顯:
type PartialFunction2[-T1,-T2,+R] = PartialFunction[Tuple2[T1,T2],R]
,但返回的類型實際上是:
scala> val f: PartialFunction2[Int,Int,Int] = {case (2,3) => 8; case (3,2) => 9}
f: PartialFunction2[Int,Int,Int] = <function1>
scala> f(2,3)
res0: Int = 8
scala> f(2,7)
scala.MatchError: (2,7) (of class scala.Tuple2$mcII$sp) ...
這是令人困惑,因爲它看起來像一個<function2>
而不是<function1>
。
另一種方法是定義PartialFunctionN
遞歸:
type PartialFunction2[-T1,-T2,+R] = PartialFunction[T1,PartialFunction[T2,R]]
但使用率不會像漂亮,乾淨像以前的例子中,我們仍然可以得到<function1>
:
scala> val g: PartialFunction2[String,String,String] = {
case "x" => {case "y" => "male"; case "x" => "female"}
}
g: PartialFunction2[String,String,String] = <function1>
scala> g("x")("y")
res0: String = male
scala> g("x")("x")
res1: String = female
scala> g("y")("x")
scala.MatchError: y (of class java.lang.String) ...
所以,基本上,我很有興趣知道是否有一個很好的理由,爲什麼斯卡拉沒有PartialFunctionN
內置,作爲獎金,我也想知道是否有辦法模仿預期的功能,並獲取而不是<function1>
作爲返回類型。
我認爲當你調用f(2,3)時,你真的調用f((2,3))。也許你可以去咖喱... –
當然它f((2,3))。很像其他任何有一個參數的函數。 'f:Function1 [Int,Int]'可以被稱爲'f(1)'或'f 1'。所以你是對的,當然! :) –
是啊,我注意到你已經嘗試了一種通過遞歸鍵入的類型... –