Last active
April 17, 2016 13:42
-
-
Save Krasnyanskiy/cf6b537d60aa369ed4cd5e2e8c80e669 to your computer and use it in GitHub Desktop.
-scala: while -> recursive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def `while`(condition: => Boolean)(command: => Unit): Unit = if (condition) { | |
command | |
`while`(condition)(command) | |
} | |
var i = 10 | |
`while`{ i = i - 1; i > 0 } { println(i) } | |
Please note that you need to call expression
in the second parentheses by name, otherwise you evaluate it only once.
Not a lazy expression
command: Unit
Since (command: => Unit)
we could do not pass an expression into the while
`while` { i = i - 1; i > 0 } {}
Compiler will add a Unit
literal ()
implicitly to { () }
. And it is just fine.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make your own
while
loop via recursion.