2013-10-04 50 views
0

比賽,我很新的斯卡拉,但我相信我已經寫了一個完全合法的Scala程序:Scala的類型不匹配錯誤時,函數簽名函數調用

這是Scala的工作表:

def product(f: Int => Int)(a: Int, b: Int): Int = 
    if (a > b) 1 // Not a 0 because the unit value of product is a 1 
    else f(a) * product(f)(a + 1, b) 

    product(x => x * x)(3, 7) 

不過,我得到以下錯誤:

> <console>:8: error: type mismatch; 
    found : Unit 
    required: Int 
      if (a > b) 1 // Not a 0 because the unit value of product is a 1 else f 
    (a) * product(f)(a + 1, b) 
     ^
> <console>:8: error: not found: value product 
       product(x => x * x)(3, 7) 
       ^

這是一個簡單的產品,從ab乘以數量的所有平方 包括的。

它說,有我的函數調用,但是,這應該是完全合法的,因爲我通過一個lambda函數返回Int。任何有關這個問題的幫助和如何處理type mismatch錯誤將深表感謝。使用Scala 2.10.2

回答

3

該工作表是以某種方式將product的主體改爲一行,因此else子句不存在。您的代碼編譯並在repl中運行。

+0

親愛的主,它適用於repl,但不適用於工作表。在學習Scala時,該工作表是不是很好用? –

0

如果使用REPL,你應該附上具體功能的身體變成這樣的括號:

def product(f: Int => Int)(a: Int, b: Int): Int = { 
    if (a > b) 1 // Not a 0 because the unit value of product is a 1 
    else f(a) * product(f)(a + 1, b) 
} 

    product(x => x * x)(3, 7) 

在其他情況下,斯卡拉REPL只看到這種函數的定義:

def product(f: Int => Int)(a: Int, b: Int): Int = if (a > b) 1 

這不正確

1

嘗試在方法主體周圍放置大括號:

def product(f: Int => Int)(a: Int, b: Int): Int = { 
    if (a > b) 1 
    else f(a) * product(f)(a + 1, b) 
} 
product(x => x * x)(3, 7) 

爲我工作。

相關問題