Caballero
Caballero

Reputation: 12101

Scala change for loop mutable aggregation to immutable

If I have this simple loop which is imperative style

val num = 100
var result = 0.0
for (i <- 0 until num) {
    result += 4.0 * (1 - (i % 2) * 2) / (2 * i + 1)
}

How would I change it to immutable and functional?

Upvotes: 0

Views: 553

Answers (2)

elm
elm

Reputation: 20415

Another approach, with a parallel collection,

(1 to 100).par.map { i => 4.0 * (1 - (i % 2) * 2) / (2 * i + 1) }.sum

Upvotes: 0

vptheron
vptheron

Reputation: 7466

You have an initial value, you iterate over a collection of values and apply an operation to each item to eventually return one single value.

This looks a lot like something that could be turned into a fold.

Upvotes: 8

Related Questions