Skip to content

Commit d253610

Browse files
committed
Add loop test with exit and continue
1 parent 964bccf commit d253610

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

tests/run/loops.scala

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import scala.util.{boundary, break}
2+
3+
object loop:
4+
5+
// We could use a boolean instead, but with `Ctrl` label types in using clauses are
6+
// more specific.
7+
enum Ctrl:
8+
case Exit, Continue
9+
10+
inline def apply(inline op: boundary.Label[Ctrl] ?=> Unit) =
11+
while boundary { op; Ctrl.Continue } == Ctrl.Continue do ()
12+
13+
inline def exit()(using boundary.Label[Ctrl]): Unit =
14+
break(Ctrl.Exit)
15+
16+
inline def continue()(using boundary.Label[Ctrl]): Unit =
17+
break(Ctrl.Continue)
18+
end loop
19+
20+
def testLoop(xs: List[Int]) =
21+
var current = xs
22+
var sum = 0
23+
loop:
24+
if current.isEmpty then loop.exit()
25+
val hd = current.head
26+
current = current.tail
27+
if hd == 0 then loop.exit()
28+
if hd < 0 then loop.continue()
29+
sum += hd
30+
sum
31+
32+
@main def Test =
33+
assert(testLoop(List(1, 2, 3, -2, 4, -3, 0, 1, 2, 3)) == 10)
34+
assert(testLoop(List()) == 0)
35+
assert(testLoop(List(-2, -3, 0, 1)) == 0)
36+
37+

0 commit comments

Comments
 (0)