score:1

Accepted answer

there can be some difficulties working with tuples.
below you can see working code, but let me explain.

val data = array((2,(2.1463120403829962,7340)), (1,(1.4532644653720025,4280)))

def tuplesum(t1: (int, (double, int)), t2: (int, (double, int))): (int, (double, int)) =
    (0,(t1._2._1 + t2._2._1, t1._2._2 + t2._2._2))

val mainmean = data.reduce(tuplesum)._2

we can introduce reduce arguments like

data.reduce((tuple1, tuple2) => tuplesum(tuple1, tuple2))

where tuple1 is kind of accumulator. on the first iteration it takes the first value of the array, and every next value adds to the value of accumulator.

so if you want to perform reduce using pattern matching it will look like this:

val mainmean = data.reduce((tuple1, tuple2) => { 
  val t1 = tuple1 match { case (i, t) => t }
  val t2 = tuple2 match { case (i, t) => t }
// now t1 and t2 represents inner tuples of input tuples
  (0, (t1._1 + t2._1, t1._2 + t2._2))}
)


upd. i rewrite previous listing adding type annotations and println statements. i hope it will help to get the point. and there is some explanation after.

val data = array((3, (3.0, 3)), (2,(2.0,2)), (1,(1.0,1)))

val mainmean = data.reduce((tuple1: (int, (double, int)),
                             tuple2: (int, (double, int))) => {
    println("tuple1: " + tuple1)
    println("tuple2: " + tuple2)

    val t1: (double, int) = tuple1 match {
        case (i: int, t: (double, int)) => t
    }
    val t2: (double, int) = tuple2 match {
        case (i: int, t: (double, int)) => t
    }
    // now t1 and t2 represents inner tuples of input tuples
    (0, (t1._1 + t2._1, t1._2 + t2._2))}
)
println("mainmean: " + mainmean)

and the output will be:

tuple1: (3,(3.0,3)) // 1st element of the array
tuple2: (2,(2.0,2)) // 2nd element of the array
tuple1: (0,(5.0,5)) // sum of 1st and 2nd elements
tuple2: (1,(1.0,1)) // 3d element
mainmean: (0,(6.0,6)) // result sum


tuple1 and tuple2 type is (int, (double, int)). we know it always be only this type, that is why we use only one case in pattern matching. we unpack tuple1 to i: int and t: (int, double). as far as we are not interested in key, we return only t. now t1 is representing the inner tuple of tuple1. the same story with tuple2 andt2.

you can find more information about fold functions here and here


Related Query

More Query from same tag