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?
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.
(0 until num).foldLeft(0.0) { (result, i) => result + 4.0 * (1 - (i % 2) * 2) / (2 * i + 1) }.
fold