How can I write function which simulates while loop? It should takes 2 arguments: condition and expression to execute.
I tried the following:
val whileLoop: (Boolean,Any)=>Unit = (condition:Boolean, expression:Any) => {
expression
if(condition) whileLoop(condition,expression)
() }
But it seems it doesn’t work, e.g. i have array:
val arr = Array[Int](-2,5,-5,9,-3,10,3,4,1,2,0,-20)
Also I have variable i:
var i = 0
I want to print all elements of arr. I can do that with the following code:
while(i<arr.length) { println(tab(i)); i+=1 }
I would like to do the same using my whileLoop function. But I can’t write function which takes reference to variable and modify that. I could pass that using array with only one element, e.g.
val nr = Array(0)
and function:
val printArray: Array[Int]=>Unit = (n:Array[Int]) => {
println(arr(n(0)))
n(0)+=1
()
}
and then using in my whileLoop:
whileLoop(nr(0)<arr.length, printArray)
After using above codes I get StackOverflowError and nr(0) is equals zero. Also following function:
val printArray: Array[Int]=>Unit = (n:Array[Int]) => {
println(arr(nr(0)))
nr(0)+=1
()
}
gives the same result.
How can i write correct function whileLoop and use that to print all arr elements?
Thanks in advance for advices.
The main problem with your implementation is that the condition and the expression are evaluated only once, when you first call
whileLoop. In the recursive call, you just pass a value, not an expression.You can solve this by using by-name arguments:
As an example:
Note that the variables
aandiare correctly referenced. Internally, the Scala compiler built a function for both the condition and the expression (block), and these functions maintain a reference to their environment.Also note that for more syntactic sugar awesomeness, you can define
whileLoopas a currified function:This allows you to call it just like an actual while loop: