Scala: how to create a new list from an operation on adjacent list items

If I have a List (1,2,3,4), I want to create a new list that is equivalent to,

List (1 + 2, 3 + 4) = List (3.7)

I need some extension to add adjacent numbers to a list and create a new list from it. I looked at the map, reduceLeft, foldLeft but couldn't find something that could do it.

+3


source to share


1 answer


The method you are looking for is grouped

, which splits the list into sublists of a given size. For example:

scala> List(1, 2, 3, 4).grouped(2).map(_.sum).toList
res0: List[Int] = List(3, 7)

      



Note that it grouped

returns an iterator, so you need to call something like toList

if you want a collection. Also note that if your list does not have an even number of elements (or, moreover, the argument is not evenly divisible by grouped

), the final list returned by the iterator may contain fewer elements than the rest.

+6


source







All Articles