Here's my function:
def sumOfSquaresOfOdd(in: Seq[Int]): Int = {
in.filter(_%2==1).map(_*_).reduce(_+_)
}
Why am I getting the error "missing parameter type for expanded function"?
Here's my function:
def sumOfSquaresOfOdd(in: Seq[Int]): Int = {
in.filter(_%2==1).map(_*_).reduce(_+_)
}
Why am I getting the error "missing parameter type for expanded function"?
map is accepting function with one parameter ((A) => B) while every _ placeholder represents a separate parameter of anonymous function (i.e. _ * _ is function with two parameters). You can use i => i * i lambda for your map function:
def sumOfSquaresOfOdd(in: Seq[Int]): Int = {
in.filter(_%2==1)
.map(i => i * i)
.reduce(_ + _)
}
Also you can use sum instead of reduce(_ + _) (note that sum will not throw for empty sequences while reduce will):
def sumOfSquaresOfOdd(in: Seq[Int]): Int = {
in.filter(_%2==1)
.map(i => i * i)
.sum
}
"map" was called with a function with two parameters when it is expecting a function of one parameter. There's another small bug due to the use of "reduce" - it throws an exception if there aren't any odd Ints in the input Seq.
A better solution would be:
def sumOfSquaresOfOdd(in: Seq[Int]): Int =
in.filter(_ % 2 == 1) . map(x => x * x) . sum
You must be using Scala2. Scala3 gives a much better error message:
Error:
2 | in.filter(_%2==1).map(_*_).reduce(_+_)
| ^^^
| Wrong number of parameters, expected: 1
(Edited to reflect changes in the other answers to this question.)
sum instead of fold or reduce