MaciejF
MaciejF

Reputation: 546

How to sum list of integers and save each step to new list?

I'm struggling to find simple-functional way to transform

val ints = List(1, 2, 3, 4, 5) into List(1, 3, 6, 10, 15)

How can it be done?

Upvotes: 2

Views: 284

Answers (5)

MaciejF
MaciejF

Reputation: 546

Thanks to Lee answer I modified it to

ints.tail.scan(ints.head)(_ + _)

Little longer but it treats first element as initial state.

Upvotes: 0

Lee
Lee

Reputation: 144206

This operation is called prefix sum, cumulative sum, or inclusive scan, the more generalized higher-order function is usually called scan. Scala provides scan as part of its collections library:

ints.scan(0)(_ + _).tail

Upvotes: 10

The Archetypal Paul
The Archetypal Paul

Reputation: 41779

Oh, go on, another way to skin the cat:

ints.drop(1).foldLeft(List(ints.head))((acc,elem)=>elem+acc.head::acc).reverse

Upvotes: 0

Chobeat
Chobeat

Reputation: 3525

ints.foldLeft(List[Int]())((acc,elem)=>elem+acc.headOption.getOrElse(0)::acc)

Upvotes: 0

Eric
Eric

Reputation: 1114

You can use foldLeft, as follows:

scala> List(1,2,3,4,5).foldLeft(List.empty[Int]) { case (acc, next) =>
     |   acc :+ next + acc.lastOption.getOrElse(0)
     | }
res6: List[Int] = List(1, 3, 6, 10, 15)

In the partial function (acc, next), acc is the currently accumulated list that starts as List.empty[Int], and next is the next value in the provided list, starting with 1.

Upvotes: 0

Related Questions