2017-02-05 241 views
3

我正在處理黑客排名問題(https://www.hackerrank.com/challenges/eval-ex),我有點卡住了。斯卡拉類型錯誤

我有一個例外是不斷上來:

Solution.scala:12: error: type mismatch; 
found : (Double, Double) => Double 
required: (AnyVal, AnyVal) => AnyVal 
       (1 to 9).reduce((total: Double, current: Double) => Math.pow(exp,current)/factNonRecursive(current)) 

那我在這Scala代碼做錯了什麼?

全碼:

object Solution { 
def factNonRecursive(num: Double): Double = { 
    (1 to (num.toInt)).foldLeft(1) ((a,b) => (a * b)) toDouble 
    } 
    def main(args: Array[String]) { 
     val sc = new java.util.Scanner (System.in); 
     var n = sc.nextInt(); 
     var a0 = 1; 
     while(a0 < n){ 
      var x = sc.nextDouble(); 
      def e(exp: Double) = { 
       (1 to 9).reduce((total: Double, current: Double) => Math.pow(exp,current)/factNonRecursive(current)) 
      } 
      println(e(x)) 
      a0+=1; 
     } 
    } 
} 

回答

4

這是因爲你有一個Range[Int],你再打上reduce,並期待一個Int,不是Double,因此編譯器推斷共同的祖先類型,這兩種是AnyVal。你需要整數第一map雙打:

(1 to 9) 
    .map(_.toDouble) 
    .reduce((_, current) => Math.pow(exp, current)/factNonRecursive(current)) 

另一種方法,而不是Range,是使用List.range(1.0, 9.0)和避免額外map

List.range(1.0, 9.0) 
    .reduce((_, current) => Math.pow(exp, current)/factNonRecursive(current)) 

此外,factNonRecursive可取代與product

(1 to num.toInt).product.toDouble 
+1

你是最偉大的。 – noname