Skip to content

Instantly share code, notes, and snippets.

@Villane
Last active December 15, 2015 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Villane/5341454 to your computer and use it in GitHub Desktop.
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 …
╒═════════════════════════╕
╎ 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);
}
@Villane
Copy link
Author

Villane commented Apr 8, 2013

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment