我正在研究黑客等级问题(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;
}
}
}
答案 0 :(得分: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