09 · Data Structures
Conditional array entries
Use if condition => value and for item in items => value inside an array. Entries are emitted eagerly in source order. False conditions omit entries; a nil value still occupies a slot. Nested arrays remain values unless explicitly spread.
On this page
Use if condition => value and for item in items => value inside an array. Entries are emitted eagerly in source order. False conditions omit entries; a nil value still occupies a slot. Nested arrays remain values unless explicitly spread.
Complete example
Conditional array entries.
// Mix ordinary values, conditional entries and loops in one array.
struct Page { title: str, enabled: bool }
let admin = true
let pages = [
Page { title: "Reports", enabled: true },
Page { title: "Drafts", enabled: false },
]
let menu = [
"Home",
if admin => "Admin",
for page in pages => if page.enabled => page.title,
]
for title in menu { print(title) }
// expected: Home
// expected: Admin
// expected: Reports
let positions = [for position, page in pages => position + 10]
print(positions[0])
// expected: 10
print(positions[1])
// expected: 11
let flattened = [0, for row in [[1, 2], [3]] => for cell in row => cell, 4]
print(flattened.len())
// expected: 5
let with_nil = [if true => nil, 7]
print(with_nil.len())
// expected: 2
Rules and behavior
Conditions and error recovery · Documentation
From a checkout of the repository:
zolo examples/features/04-control-flow/24-array-entries.zolo
Keeping only matching entries
A filtering builder skips failed readings before evaluating the entry. The example counts evaluations to show that the failed reading does no work.
// Failed readings produce neither an entry nor a body evaluation.
let readings: [Result<int, str>] = [.Ok(3), .Err("offline"), .Ok(5)]
var evaluated = 0
fn double(value: int) -> int { evaluated += 1; value * 2 }
let values = [for case .Ok(value) in readings => double(value)]
print(values[0]) // expect: 6
print(values[1]) // expect: 10
print(values.len()) // expect: 2
print(evaluated) // expect: 2
let indexed = #{for case .Ok(value) in readings => [value]: value * 2}
print(indexed[3]) // expect: 6
print(indexed[5]) // expect: 10
See also