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"?
CodePudding user response:
I guess because map
wants a function of a single argument, and you ask it to call *
with two arguments. Replace _ * _
with arg => arg * arg
and retry.
CodePudding user response:
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(_ _)
}
CodePudding user response:
The solutions by @chrnybo and @Guru Stron are fairly good ones and they do solve the original problem - that "map" was called a function with two arguments when it is expecting a function of one argument. But both have a small bug due to the use of "reduce" - they throw an exception if there aren't any odd Ints in the input Seq.
A little better solution might be:
def sumOfSquaresOfOdd(in: Seq[Int]): Int =
in.filter(_ % 2 == 1) . map(x => x * x) . foldLeft(0)(_ _)