Last active
December 15, 2015 23:39
-
-
Save Villane/5341454 to your computer and use it in GitHub Desktop.
Another Slang example. As there are no mutable members / variables (yet), we must use functional concepts for things like iteration. This program prints 12345 twice. Due to use of names like next() and hasNext(), the content of the loop should be before the while statement. The loop will be continued with the Range returned from i.next() and so …
This file contains 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
╒═════════════════════════╕ | |
╎ Range class ╎ | |
╘═════════════════════════╛ | |
val class Range (from: Int, to: Int) { | |
def hasNext() = from < to | |
def valid() = from <= to | |
def current() = from | |
def next() = Range(from + 1, to) | |
} | |
extending Int { | |
def to(that: Int) = Range(this, that) | |
} | |
╒═════════════════════════╕ | |
╎ Range example ╎ | |
╘═════════════════════════╛ | |
def main() = { | |
/* This is more like a do-while loop. It assumes ranges are never empty. */ | |
loop(i := 1 to 5) { | |
printNumber(i.current()); | |
while (i.hasNext()) do i.next() | |
} | |
/* This is like a normal while loop. If I could come up with better names, this might be better. */ | |
loop(i := 1 to 5) while i.valid() do { | |
printNumber(i.current()); | |
i.next() | |
} | |
/* Once I add some kind of for-comprehensions, it could generate a similar loop with syntax like below */ | |
//for (i <- 1 to 5) printNumber(i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can also think of the loop as a tail-recursive anonymous function, except it never compiles to a function. Actually it gets expanded to:
loop(i: Range := 1 to 5)
if i.valid() then {
printNumber(i.current());
continue(i.next())
} else break()
Where continue and break are magic functions that are only available inside loop bodies.