Skip to content

std/generative

Import: use "std/generative";

Stateful generative pattern sources. The cycle-callback helpers are part of the prelude (always in scope); the stream and Markov sources need use "std/generative";.

Per-cycle callbacks.

Register functions that fire once per cycle on the interpreter thread with on_cycle, and clear them with off_cycle. Each callback receives the cycle number being prepared, making it the hook for generative, evolving patterns. These helpers are always in scope; the stateful stream and Markov sources need use "std/generative";.

fn off_cycle() -> NUL

Clear all per-cycle callbacks registered via on_cycle().

Returns: NUL — nothing

fn on_cycle(callback: Function) -> NUL

Register a per-cycle callback that runs on the interpreter thread. The callback receives the cycle number being prepared (not the current playing cycle). Multiple callbacks can be registered; they fire in registration order. Changes to the callback list (via on_cycle/off_cycle) within a callback take effect on the next cycle, not the current one.

Parameters:

  • callback (Function) — takes (cycle) and is called once per cycle

Returns: NUL — nothing

fn prime_cycles() -> NUL

Fire cycle callbacks once (for cycle 0) to set initial patterns. Called automatically by PLAY for internal clock. Call manually before external MIDI clock playback to ensure patterns are ready when the first cycles play.

Returns: NUL — nothing

Stateful generative pattern functions.

Pattern sources that carry state between cycles, driven by seeded randomness (std/random).

fn markov(num_states: Number, transitions: Array, initial: Number) -> Pattern

Creates a Markov chain pattern with cycle-seeded transitions.

Parameters:

  • num_states (Number) — number of states (positive integer)
  • transitions (Array) — transition matrix (array of rows, each summing to 1)
  • initial (Number) — initial state index (0-based)

Returns: Pattern — a pattern emitting the chain’s state, advanced once per cycle

fn stream(initial: Note or Number or Array or Pattern, next_fn: Function) -> Pattern

Creates a stateful stream pattern from an initial value and a next function. Each cycle’s output depends on the previous cycle’s state, enabling “walking” patterns like melodic random walks.

Parameters:

  • initial (Note | Number | Array | Pattern) — initial value
  • next_fn (Function) — takes (prev, cycle) and returns the next value

Returns: Pattern — a pattern that evolves its state once per cycle