Functional Language Features: Iterators and Closures

Oxide's design incorporates ideas from many existing languages and paradigms, and functional programming has significantly influenced its design. Programming in a functional style often includes using functions as values by passing them in arguments, returning them from other functions, assigning them to variables for later execution, and so forth.

In this chapter, we'll cover two powerful features that enable functional programming patterns in Oxide:

  • Closures: Anonymous functions that can capture their environment, with a clean { params -> body } syntax
  • Iterators: A way of processing a series of elements lazily and efficiently

We'll also explore how closures and iterators enable you to write clear, expressive code that's also fast. You'll learn that these high-level abstractions compile down to code that's just as efficient as what you might write by hand.

Closures and iterators are central to idiomatic Oxide code. Mastering them will help you write code that's both elegant and performant.

What You'll Learn

Closures

Oxide's closure syntax is inspired by Swift and Kotlin, using curly braces and an arrow:

// Rust closure: |x| x * 2
// Oxide closure:
let double = { x -> x * 2 }

// Trailing closures with implicit `it`
items.filter { it > 0 }.map { it * 2 }

You'll learn:

  • How to define closures with various parameter forms
  • How closures capture values from their environment
  • The three Fn traits that determine how closures interact with captured values
  • The implicit it parameter for concise trailing closures

Iterators

Iterators provide a powerful, lazy way to process sequences of values:

let sum = numbers
    .iter()
    .filter { it % 2 == 0 }
    .map { it * it }
    .sum()

You'll learn:

  • How iterators work under the hood
  • Consuming adaptors that produce final values
  • Iterator adaptors that transform iterators
  • How to create your own custom iterators

Performance

A common concern with high-level abstractions is runtime overhead. You'll learn:

  • Why Oxide's iterators and closures are "zero-cost abstractions"
  • How the compiler optimizes iterator chains
  • When to use iterators vs. traditional loops (spoiler: iterators are usually just as fast)

Let's start by exploring closures in depth.