1

Below code demonstrates two methods of summing a value where the termination condition is if the value reaches 5 :

 object ob extends App { def withoutRecursion = { var currentTotal = 0.0; while(5 > currentTotal){ currentTotal = currentTotal + scala.util.Random.nextFloat println(currentTotal); } } def withRecursion = { var currentTotal = 0.0; def whileLoop(cond : =>Boolean)(block : =>Unit) : Unit = if(cond) { block whileLoop(cond)(block) } whileLoop(5 > currentTotal) { currentTotal = currentTotal + scala.util.Random.nextFloat println(currentTotal); } } } 

Is the withRecursion method the idiomatic method of replacing a while loop with a functional programming style in this case ?

1 Answer 1

6

Not really. In your examples you are still using a var to collect the intermediate results. That's not very FP.

One (of many) options is to create an infinite, but lazy, Stream to repeat the necessary calculations. Then if you want all the intermediate values you takeWhile(), or if you want just the end result you dropWhile().

Example:

Stream.iterate(0F)(_ + util.Random.nextFloat).takeWhile(_ < 5) 

This creates a finite Stream with all the values from 0.0 to the largest sum less than 5.

On the other hand ...

Stream.iterate(0F)(_ + util.Random.nextFloat).dropWhile(_ < 5).head 

... this will give you the first result greater than 5.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.