Last active
October 6, 2024 15:38
-
-
Save bishabosha/95880882ee9ba6c53681d21c93d24a97 to your computer and use it in GitHub Desktop.
Scala break/continue zero-cost loop abstraction
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
//> using scala "3.3.0" | |
import scala.util.boundary, boundary.break | |
object Loops: | |
type ExitToken = Unit { type Exit } | |
type ContinueToken = Unit { type Continue } | |
type Exit = boundary.Label[ExitToken] | |
type Continue = boundary.Label[ContinueToken] | |
object loop: | |
inline def apply(inline op: (Exit, Continue) ?=> Unit): Unit = | |
boundary[ExitToken]: | |
while true do | |
boundary[ContinueToken]: | |
op | |
inline def exit()(using Exit) = break(().asInstanceOf[ExitToken]) | |
inline def continue()(using Continue) = break(().asInstanceOf[ContinueToken]) |
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
import Loops.* | |
@main def oddsUpToLimit(limit: Int) = | |
var i = 0 | |
loop: | |
i += 1 | |
if i == limit then loop.exit() | |
if i % 2 == 0 then loop.continue() | |
println(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment