Skip to content

Functional Programming

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 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 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 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 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 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

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:

  1. Readable: each step describes one transformation
  2. Composable: add or remove steps without restructuring
  3. Verifiable: contracts can be attached at each stage
  • Iterators — the for-in loop and iterator protocol
  • Closures — closures and variable capture
  • Contracts — add requires/ensures to pipeline functions