Ben Nelson Ben Nelson - 4 years ago 104
Scala Question

Scala type error

I'm working on a Hacker Rank problem (https://www.hackerrank.com/challenges/eval-ex) and I got a bit stuck.

I have an exception that keeps coming up:

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))


What am I doing wrong in this Scala code?

Full Code:

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;
}
}
}

Answer Source

This happens because you have a Range[Int], which you later call reduce on and it expects an Int, not a Double, hence the compiler is inferring the common ancestor type for both which is AnyVal. You'll need to map the integers to doubles first:

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

Another approach, instead of Range, would be to use List.range(1.0, 9.0) and avoid the additional map:

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

Additionally, factNonRecursive can be substituted with product:

(1 to num.toInt).product.toDouble
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download