Functional Programming
Functional Combinators
Kōdo provides functional combinators on lists that let you transform, filter, and aggregate data declaratively. These combinators compose into pipelines that are expressive and easy for both AI agents and humans to reason about.
map — Transform Elements
map applies a closure to each element, producing a new list:
let numbers: List<Int> = list_new()
list_push(numbers, 1)
list_push(numbers, 2)
list_push(numbers, 3)
let doubled: List<Int> = numbers.map(|x: Int| -> Int { x * 2 })
// doubled contains [2, 4, 6]
filter — Select Elements
filter keeps only elements where the predicate returns true:
let numbers: List<Int> = list_new()
list_push(numbers, 1)
list_push(numbers, 2)
list_push(numbers, 3)
list_push(numbers, 4)
let evens: List<Int> = numbers.filter(|x: Int| -> Bool { x % 2 == 0 })
// evens contains [2, 4]
fold — Aggregate to a Single Value
fold reduces a collection to a single value by applying a combining function:
let numbers: List<Int> = list_new()
list_push(numbers, 1)
list_push(numbers, 2)
list_push(numbers, 3)
let sum: Int = numbers.fold(0, |acc: Int, x: Int| -> Int { acc + x })
// sum is 6
The first argument is the initial accumulator value. The closure receives the current accumulator and the next element, and returns the new accumulator.
any — Check If Any Match
any returns true if at least one element satisfies the predicate:
let numbers: List<Int> = list_new()
list_push(numbers, 1)
list_push(numbers, 2)
list_push(numbers, 3)
let has_even: Bool = numbers.any(|x: Int| -> Bool { x % 2 == 0 })
// has_even is true
all — Check If All Match
all returns true if every element satisfies the predicate:
let numbers: List<Int> = list_new()
list_push(numbers, 2)
list_push(numbers, 4)
list_push(numbers, 6)
let all_even: Bool = numbers.all(|x: Int| -> Bool { x % 2 == 0 })
// all_even is true
Composing Pipelines
Combinators chain naturally to form data processing pipelines:
let data: List<Int> = list_new()
list_push(data, 1)
list_push(data, 2)
list_push(data, 3)
list_push(data, 4)
list_push(data, 5)
// Filter even numbers, double them, then sum
let evens: List<Int> = data.filter(|x: Int| -> Bool { x % 2 == 0 })
let doubled: List<Int> = evens.map(|x: Int| -> Int { x * 2 })
let result: Int = doubled.fold(0, |acc: Int, x: Int| -> Int { acc + x })
// result is 12 (2*2 + 4*2)
This pipeline is:
- Readable: each step describes one transformation
- Composable: add or remove steps without restructuring
- Verifiable: contracts can be attached at each stage
Examples
functional_pipeline.ko— chained combinator pipelinesiterator_map_filter.ko—mapandfilterusageiterator_fold.ko—foldfor aggregationclosures_functional.ko— higher-order functionsword_counter.ko— real-world pipeline with string ops and fold