Search code examples
scalaparametersfoldleft

Scala foldLeft too many parameters


I have a list of tuples called item, each index in the list contains 2 x Doubles e.g.

item = ((1.0, 2.0), (3.0, 4.0), (10.0, 100.0))

I want to perform a calculation on each index within the list item and I'm trying to do it with foldLeft. This is my code:

item.foldLeft(0.0)(_ + myMethod(_._2, _._1, item.size)))

_._2 accesses the current item Tuple at index 1 and _._1 accesses the current item Tuple at index 0. e.g. for the first fold it should effectively be:

item.foldLeft(0.0)(_ + myMethod(2.0, 1.0, item.size)))

The Second Fold:

item.foldLeft(0.0)(_ + myMethod(4.0, 3.0, item.size)))

The Third Fold:

item.foldLeft(0.0)(_ + myMethod(100.0, 10.0, item.size)))

where myMethod:

def myMethod(i: Double, j:Double, size: Integer) : Double = {
  (j - i) / size
  }

It is giving me an error which says that there are too many parameters for foldLeft as it requires 2 parameters. myMethod returns a Double, and _ is a Double. So, where is this extra parameter the compiler is seeing?

If I do this:

item.foldLeft(0.0)(_ + _._1))

It sums up all the first Doubles in each index of item - replacing _._1 with _._2 sums up all the second Doubles in each index of item.

Any help is greatly appreciated!


Solution

  • Each _ is equivalent to a new argument, so (_ + myMethod(_._2, _._1, item.size)) is an anonymous function with 3 arguments: (x, y, z) => x + myMethod(y._2, z._1, item.size).

    What you want is (acc, x) => acc + myMethod(x._2, x._1, item.size).