Loops
Draft provides several looping constructs for iteration.
For Loop
Section titled “For Loop”Iterate over a range or collection:
@// Range iterationfor @i in 0..10 write(@i)fin for.
@// Exclusive rangefor @i in 0..<10 write(@i)fin for.Iterating Arrays
Section titled “Iterating Arrays”@fruits = ["apple", "banana", "cherry"]for @fruit in @fruits write(@fruit)fin for.Iterating with Index
Section titled “Iterating with Index”for @index, @fruit in @fruits write(string(@index) + ": " + @fruit)fin for.Iterating Maps
Section titled “Iterating Maps”@scores = {"Alice": 95, "Bob": 87, "Charlie": 92}for @name, @score in @scores write(@name + ": " + string(@score))fin for.Iterating Strings
Section titled “Iterating Strings”for @char in "Hello" write(@char)fin for.While Loop
Section titled “While Loop”Execute while a condition is true:
mut @count = 0while @count < 10 write(@count) @count = @count + 1fin while.Infinite Loop
Section titled “Infinite Loop”while true @input = read_line() if @input == "quit" break fin if. process(@input)fin while.Loop Control
Section titled “Loop Control”Exit the loop immediately:
for @i in 0..100 if @i == 50 break fin if. write(@i)fin for.Continue
Section titled “Continue”Skip to the next iteration:
for @i in 0..10 if @i % 2 == 0 continue fin if. write(@i) @// Only odd numbersfin for.Break with Value
Section titled “Break with Value”Return a value from a loop:
@result = for @i in 0..100 if @i > 50 break @i fin if.fin for.@// result = 51Nested Loops
Section titled “Nested Loops”for @i in 0..3 for @j in 0..3 write(string(@i) + "," + string(@j)) fin for.fin for.Labeled Loops
Section titled “Labeled Loops”Break or continue outer loops:
outer: for @i in 0..10 inner: for @j in 0..10 if @i * @j > 50 break outer fin if. fin for.fin for.Loop Expressions
Section titled “Loop Expressions”Loops can return values:
@sum = for @i in 1..10 @i * @ifin for.@// sum = 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100 = 385Iterators
Section titled “Iterators”Create custom iterators:
record Counter current: Int max: Intfin record.
impl Iterator for Counter action next(@self: Counter) -> Option<Int> if @self#current < @self#max @value = @self#current @self#current = @self#current + 1 return some(@value) fin if. return none fin action.fin impl.
@counter = Counter { current: 0, max: 10 }for @value in @counter write(@value)fin for.Common Patterns
Section titled “Common Patterns”Collect Results
Section titled “Collect Results”@squares = for @i in 1..10 @i * @ifin for.@// squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Find First Match
Section titled “Find First Match”@first_even = for @i in 1..100 if @i % 2 == 0 break @i fin if.fin for.@// first_even = 2Filter and Transform
Section titled “Filter and Transform”@evens_squared = for @i in 1..20 if @i % 2 == 0 @i * @i fin if.fin for.