Control Flow
if/else, while, for loops, break, and continue.
Achronyme provides standard control flow constructs. if/else is an expression that returns a value. Loops come in three forms: while, forever, and for..in.
if / else
if/else blocks are expressions — they evaluate to the last expression in the taken branch. An if without else returns nil when the condition is false.
let x = if true { 10 } else { 20 }
assert(x == 10)
let min = if 3 < 5 { 3 } else { 5 }
assert(min == 3)
Chain conditions with else if:
let grade = 85
mut ltr = "F"
if grade >= 90 {
ltr = "A"
} else if grade >= 80 {
ltr = "B"
} else if grade >= 70 {
ltr = "C"
}
assert(ltr == "B")
if/else chains are also expressions:
let val = if false {
1
} else if true {
42
} else {
99
}
assert(val == 42)
while
Repeats a block while the condition is true.
mut sum = 0
mut i = 1
while i <= 10 {
sum = sum + i
i = i + 1
}
assert(sum == 55)
forever
An infinite loop. Use break to exit.
mut count = 0
forever {
count = count + 1
if count == 5 { break }
}
assert(count == 5)
for..in
Iterates over a range or a collection.
Range form — start..end (exclusive upper bound):
mut sum = 0
for i in 0..5 {
sum = sum + i
}
assert(sum == 10)
Collection form — iterates over arrays or keys(map):
mut total = 0
for x in [10, 20, 30] {
total = total + x
}
assert(total == 60)
let scores = {math: 95, science: 88, english: 92}
mut sum = 0
for k in keys(scores) {
sum = sum + scores[k]
}
assert(sum == 275)
break
Exits the innermost loop immediately.
mut found = -1
mut pos = 0
let haystack = [5, 3, 8, 1, 9]
for val in haystack {
if val == 8 {
found = pos
break
}
pos = pos + 1
}
assert(found == 2)
break only affects the innermost loop in nested structures:
mut outer = 0
mut total = 0
while outer < 3 {
mut inner = 0
forever {
inner = inner + 1
total = total + 1
if inner == 2 { break }
}
outer = outer + 1
}
assert(total == 6)
continue
Skips the rest of the current iteration and moves to the next one.
mut odds = 0
mut k = 0
while k < 10 {
k = k + 1
if k % 2 == 0 { continue }
odds = odds + 1
}
assert(odds == 5)
Quick Reference
| Construct | Syntax | Notes |
|---|---|---|
| if/else | if cond { a } else { b } | Expression — returns a value |
| else if | if c1 { } else if c2 { } else { } | Chainable |
| while | while cond { body } | Standard loop |
| forever | forever { body } | Must break to exit |
| for..in range | for i in 0..n { body } | Exclusive upper bound |
| for..in collection | for x in arr { body } | Arrays, keys(map) |
| break | break | Exits innermost loop |
| continue | continue | Skips to next iteration |