2012-06-10 66 views
10

我有幾個有關咖喱功能的問題。在這裏,我要求他們一個接一個斯卡拉咖喱功能相關的問題

1)http://twitter.github.com/scala_school/basics.html給出了一個curried函數的例子 - 我認爲這是一個函數定義,但事實上並非如此。 REPL根本不承認這是一個有效的陳述。

multiplyThenFilter { m: Int => m * 2 } { n: Int => n < 5} 

2)爲什麼我們不能從部分參數化的方法定義函數?即以下定義出了什麼問題?

scala> def multiply(m: Int, n: Int): Int = m * n 
multiply: (m: Int, n: Int)Int 

scala> val timesTwo = multiply(2,_) 
<console>:11: error: missing parameter type for expanded function ((x$1) => multiply(2, x$1)) 
     val timesTwo = multiply(2,_) 
           ^

3)爲什麼我們不能創建一個部分參數化的函數curry?即以下定義出了什麼問題?

scala> (multiply(_,_)).curried 
    res13: Int => (Int => Int) = <function1> // THIS IS OK 

scala> (multiply(20,_)).curried 
<console>:12: error: missing parameter type for expanded function ((x$1) => multiply(20, x$1)) 
       (multiply(20,_)).curried 
         ^
+0

1)它是無效的,因爲它必須首先聲明。例如,像這樣:'def multiplyThenFilter(a:Int => Int)(b:Int => Boolean)= {List(1,2,3,4).map(a)。過濾器(b)}' –

+0

1)multiplyThenFilter現在不見了。你是不是被它迷惑:-) –

回答

11

問題1

斯卡拉學校例子混亂,這絕對不是一個定義。在GitHub上打開它的an issue,所以也許這是一個錯誤。你能想象一個合理的解釋可能是這樣的:

def multiplyThenFilter(f: Int => Int)(p: Int => Boolean): Int => Option[Int] = { 
    i => 
    val j = f(i) 
    if (p(j)) Some(j) else None 
} 

(或等同,f andThen (Some(_) filter p)。)

那麼例子是雙打其輸入並返回結果的Some如果它是一個功能小於5,否則爲None。但是,除非對此問題有所迴應,否則沒人確切知道作者的意圖。


問題2

timesTwo不工作僅僅是Scala的編譯器不支持那種類型的推理,見this questionmy answer there了一下相關細節的原因。你需要去與下列之一:

def multiply(m: Int, n: Int): Int = m * n  
val timesTwo = multiply(2, _: Int) 

def multiply(m: Int)(n: Int): Int = m * n  
val timesTwo = multiply(2) _ 

即,如果你想在這裏的類型推斷,你需要使用多個參數列表。否則,你必須幫助編譯器解決這個問題。


問題3

關於第三個問題,假設我們有以下的,以避免在您的第二個問題的問題:

val timesTwo = multiply(2, _: Int) 

這是一個Function1,剛剛沒有按」沒有curried方法 - 你需要一個Function2(或Function3等)。

只用一個參數來討論一個函數就沒有意義。 Currying接受一個具有多個參數的函數,併爲您提供一個函數,它接受一個返回另一個函數的單個參數(它本身可能接受一個參數並返回另一個函數等)。

+0

的唯一的人是兩個功能「timesTwo」中定義爲「VAL timesTwo =乘(2,_:智力)」和「VAL timesTwo =乘(2)_」在你的答案問題2與同一類型? – chen

+0

是的,它們都是'Int => Int'(或者等價於'Function1 [Int,Int]')。 –