Iterators
Iterators
Section titled “Iterators”Kōdo provides a built-in iterator protocol that lets you traverse collections using for-in loops. Lists, Maps, and Strings all support iteration.
The for-in Loop
Section titled “The for-in Loop”The simplest way to iterate is with for-in:
let items: List<Int> = list_new()list_push(items, 10)list_push(items, 20)list_push(items, 30)
for item in items { print_int(item)}Output:
102030Iterating Over Lists
Section titled “Iterating Over Lists”for-in on a List<Int> visits each element in order:
let items: List<Int> = list_new()list_push(items, 10)list_push(items, 20)list_push(items, 30)
for item in items { print_int(item)}for-in works with both List<Int> and List<String>.
Iterating Over Map Keys
Section titled “Iterating Over Map Keys”for-in on a Map<Int, Int> iterates over the keys:
let scores: Map<Int, Int> = map_new()map_insert(scores, 1, 95)map_insert(scores, 2, 87)
for key in scores { print_int(key)}You can also use map_contains_key and map_get for direct lookups:
if map_contains_key(scores, 1) { print_int(map_get(scores, 1))}Iterator Protocol
Section titled “Iterator Protocol”Under the hood, for-in desugars to the iterator protocol:
- Call
.iter()on the collection to get an iterator handle - Call
advance()on the iterator — returns1if an element is available,0if exhausted - Call
value()on the iterator to get the current element - Repeat until
advance()returns0 - Call
free()on the iterator to clean up
You don’t normally need to use the protocol directly — for-in handles it automatically.
Range-Based Iteration
Section titled “Range-Based Iteration”You can iterate over a range of integers using a while loop or by building a list:
let i: Int = 0while i < 10 { print_int(i) i = i + 1}Examples
Section titled “Examples”for_in.ko— for-in loops over collectionsiterator_basic.ko— basic iterator protocoliterator_list.ko— iterating overList<T>iterator_map_filter.ko—mapandfilteron iteratorsiterator_fold.ko—foldfor aggregationiterator_map.ko— iterating overMapkeysiterator_string.ko— iterating overStringcharacters
Next Steps
Section titled “Next Steps”- Functional Combinators —
map,filter,fold, and pipeline composition - Closures — closures and higher-order functions
- Data Types — structs, enums, and pattern matching