3

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"?

1

3 Answers 3

4

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh wow I had already tried that earlier and it didn't work, but now I tried it, closed the IDE and opened it again, and it works. Why must programming be this way. Thanks for your help.
2

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.

Comments

2

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

4 Comments

Thanks, Patrick. Care to also explain the wording of OPs error message; "missing parameter type for expanded function", what tricks Scala into reporting it this way?
Sorry, I don't have any idea. But see my edits to my original answer.
or just sum instead of fold or reduce
Very good point @Guru Stron. I edited my answer to include your improvement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.