0

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?

1
  • 3
    Have you tried to solve this yourself before asking here? Paste a code snippet of your attempts before asking for the answer. I'll give you a hint, you're looking for a fold Commented Jun 17, 2014 at 14:20

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Might be worth providing the code that does the folding, in case he's never seen a fold before: (0 until num).foldLeft(0.0) { (result, i) => result + 4.0 * (1 - (i % 2) * 2) / (2 * i + 1) }.
0

Another approach, with a parallel collection,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.