Example of the Scala aggregate function

前端 未结 7 940
傲寒
傲寒 2020-12-22 19:07

I have been looking and I cannot find an example or discussion of the aggregate function in Scala that I can understand. It seems pretty powerful.

Can t

7条回答
  •  天命终不由人
    2020-12-22 19:29

    Just to clarify explanations of those before me, in theory the idea is that aggregate should work like this, (I have changed the names of the parameters to make them clearer):

    Seq(1,2,3,4).aggragate(0)(
         addToPrev = (prev,curr) => prev + curr, 
         combineSums = (sumA,sumB) => sumA + sumB)
    

    Should logically translate to

    Seq(1,2,3,4)
        .grouped(2) // split into groups of 2 members each
        .map(prevAndCurrList => prevAndCurrList(0) + prevAndCurrList(1))
        .foldLeft(0)(sumA,sumB => sumA + sumB)
    

    Because the aggregation and mapping are separate, the original list could theoretically be split into different groups of different sizes and run in parallel or even on different machine. In practice scala current implementation does not support this feature by default but you can do this in your own code.

提交回复
热议问题