effekt-lang / effekt

A research language with effect handlers and lightweight effect polymorphism

Home Page:https://effekt-lang.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

loop with early return

IR0NSIGHT opened this issue · comments

Feature request:
a for loop with ability to return early/break

Right now there is no such feature (afaik):
each(n,m) executes from start to finish, no option to break early.

In order to use a return early functionality (as is dictated in my case by the existing are-we-fast-yet benchmarks) i have to fall back to "while (run)" ... and mutate run in the loop:

var run = true
while (run) {
   if (...) { run = false}
}

This is much harder to read/understand/verify and invites bugs (mutable state and unnecessary while loop)

so:
each() with break (and continue) would be nice to have.
(any kind of early return would suffice, it doesnt have to be "break")

Thanks for the issue!
I'm putting some additional context below:

Existing related work

The ML backend has a Control effect:

effect Control {
def break(): Unit
def continue(): Unit
}

and a function each that allows one to use the Control effect and handles it correctly:

def each(start: Int, end: Int) { action: (Int) => Unit / Control } = {

I don't know if we want to port this version of each to the JavaScript backend as well 🤔
Related to #309

Examples

def greaterFifteen() = {
var total = 0;
each(0, 100) { i =>
total = total + i;
if (total > 15) do break()
println(i)
}
}
def sumPositive() = {
var total = 0;
each(-10, 10) { i =>
if (i < 0) do continue()
total = total + i
}
println(total)
}