Skip to content

Control Flow

if condition {
// then branch
}
if condition {
// then
} else {
// else
}
if x < 0 {
print("negative")
} else if x == 0 {
print("zero")
} else {
print("positive")
}
let count = 5
// This works
if count > 0 {
print("has items")
}
// This does NOT work
// if count { ... } // Error: condition must be boolean

Iterate over arrays:

let items = ["apple", "banana", "cherry"]
for item in items {
print(item)
}

Iterate over ranges:

// 1 to 5 inclusive
for i in 1..5 {
print(i) // 1, 2, 3, 4, 5
}

Control how AI context is managed in loops. The modifier goes after the closing brace:

// Default: keep full history
for item in items {
do "Process {item}"
}
// Forget: clear AI context each iteration
for item in items {
do "Process {item}"
} forget
// Compress: summarize context to save tokens
for item in items {
do "Process {item}"
} compress
// Verbose: explicitly keep full history (default)
for item in items {
do "Process {item}"
} verbose

See Context Management for more details.

let count = 0
while count < 10 {
print(count)
count = count + 1
}

The break statement exits the innermost loop immediately:

for i in [1, 2, 3, 4, 5] {
if i == 3 {
break
}
print(i) // prints 1, 2
}

Works in both for-in and while loops:

let i = 0
while i < 100 {
i = i + 1
if i == 5 {
break
}
}
// i is now 5

break only exits the innermost loop:

for i in [1, 2, 3] {
for j in [1, 2, 3, 4, 5] {
if j == 2 {
break // only exits inner loop
}
print(j) // prints 1 for each outer iteration
}
print("outer") // still runs 3 times
}

Loops are powerful when combined with AI expressions:

let topics = ["AI", "Climate", "Space"]
let summaries: text[] = []
for topic in topics {
let summary = do "Write a one-sentence summary about {topic}"
summaries.push(summary)
}

Use forget when processing many items to avoid context overflow:

for article in articles {
let analysis = do "Analyze this article: {article}"
results.push(analysis)
} forget