Skip to content

Instantly share code, notes, and snippets.

@andiogenes
Last active June 24, 2024 10:50
Show Gist options
  • Save andiogenes/4e47bae8ccc2e9775dc21f5dc036f13e to your computer and use it in GitHub Desktop.
Save andiogenes/4e47bae8ccc2e9775dc21f5dc036f13e to your computer and use it in GitHub Desktop.
// Emulating loop breaks with loop condition
object A {
def main(args: Array[String]) = {
val start = System.currentTimeMillis
val until = Int.MaxValue
var i = 0
var c = 0
while (i < until) {
var j = 0
var cont = true
while (cont) {
if (j >= i) {
c += 1
cont = false
} else {
j += 1
}
}
i += 1
}
println(c)
println(System.currentTimeMillis - start)
}
}
2147483647
4204
import scala.util.boundary
import boundary.{Label, break}
// Breaking the loop with `boundary/break`
object B {
def main(args: Array[String]) = {
val start = System.currentTimeMillis
val until = Int.MaxValue
var i = 0
var c = 0
while (i < until) {
boundary {
var j = 0
while (true) {
if (j >= i) {
c += 1
break()
}
j += 1
}
}
i += 1
}
println(c)
println(System.currentTimeMillis - start)
}
}
2147483647
127
import scala.util.boundary
import boundary.{Label, break}
// Non-local `boundary/break`
object C {
def main(args: Array[String]) = {
val start = System.currentTimeMillis
val until = Int.MaxValue
var i = 0
var c = 0
while (i < until) {
boundary {
for (j <- Iterator.from(0)) {
if (j >= i) {
c += 1
break()
}
}
}
i += 1
}
println(c)
println(System.currentTimeMillis - start)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment