Reputation: 956
I'm not sure where to ask this... (it doesn't quite fit the code-golf stackoverflow community)
I have this proof-of-concept javascript snippet that loops without for/while loops by using recursion:
(x=>x(x))(x=>{console.log('...'); x(x);})
Is there an equivalent one-liner scala snippet that would do the same? (again, using only recursion to achieve looping)?
Upvotes: 0
Views: 113
Reputation: 369458
Using recursion for looping is the standard way of doing iteration in any functional language, Scala and ECMAScript or by no means special in this regard. And implementing this is a typical beginner's exercise. In Scala, it might look something like this:
@scala.annotation.tailrec
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
if (condition) {
body
whileLoop(condition)(body)
}
var i = 10
var j = 100
whileLoop { i < j } {
println(i)
i += 1
j -= 1
}
Now, you might say "But wait, that's not on one line!" But here's the thing: that's a meaningless requirement because all code can always be condensed into one line by removing line breaks:
@scala.annotation.tailrec def whileLoop(condition: => Boolean)(body: => Unit): Unit = if (condition) { body; whileLoop(condition)(body) }; var i = 10; var j = 100; whileLoop { i < j } { println(i); i += 1; j -= 1 }
Upvotes: 0
Reputation: 22850
Well, you can do this:
def loop(): Unit = { println("loop"); loop() }
Or this:
def loop[A](f: (A => A) = (loop[A] _)): A = { println("loop"); loop(f) }
But I do not see what is the value, it is just a dumb infinite function.
Upvotes: 5