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.