Flow

Standard Library

Flow’s standard library is split across a small kernel of always-on C# built-ins and a set of opt-in .flow modules that you bring in with use "@name". This page is the navigation index — it lists every module, what it provides, and which dedicated wiki page covers it in depth.

For the mechanics of use and local-file imports, see Imports and Modules.

Why use "@std" Matters

Without use "@std", you only have raw language syntax (variables, prefix arithmetic via (add) etc., proc, note streams, context blocks). Essential functions like print, str, concat, list, map, filter, and all collection operations require the standard library.

use "@std"
(print "now print works")
Open in playground

Module Index

ModuleImportProvidesWiki Page
core (auto)noneArithmetic, comparisons, logic, math, random, if, eval, lambdasLanguage Basics
@stduse "@std"I/O, str, concat, type conversion, transitively re-exports @collections and @barsthis page
@collectionsuse "@collections"List operations (head, tail, map, filter, reduce, …)Collections
@barsuse "@bars"Bar/note primitivesNote Streams
@audiouse "@audio"Buffers, signal generation, envelopes, effects, playback, WAV/MIDI I/O, granular / stretch / pitchShift, vocalizationAudio and Synthesis, Effects, Playback and Export, Vocalization
@notationuse "@notation"Note-value constants, MusicalNote constructors, Bar / Sequence builders, time-signature presetsNote Streams
@compositionuse "@composition"DAW-style timeline (setBPM, createVoice, createTrack), polyrhythm, tempoRamp, vary, renderSongVoices and Tracks, Pattern Transforms, Generative Music
@patternsuse "@patterns"13 Tidal-style combinators on Sequence (every, fast, slow, jux, sometimes, …)Generative Music
@generativeuse "@generative"Markov chains, L-systems, cellular automata, chaos mapsGenerative Music
@improvuse "@improv"jam chord-aware Markov improvisation + composer-editable style packsGenerative Music
@sfzuse "@sfz"SFZ orchestral sampler — loadSfz, 20-entry GM symbol dictAudio and Synthesis
@notation-iouse "@notation-io"writeMusicXML, writeLilyPond export; abc, mml importPlayback and Export
@testuse "@test"Test framework + assertion procsTips and Tricks

@std automatically imports @collections and @bars, so you rarely need to import them separately.

Runtime Gates

Two modules flip runtime gates on ExecutionContext when imported:

  • @sfz sets SfzEnabled = true. Calling loadSfz without use "@sfz" first raises a "loadSfz requires \use \“@sfz\”`”` error rather than a generic “function not found”.
  • @notation-io sets NotationIoEnabled = true. Calling writeMusicXML / writeLilyPond / abc / mml without the import behaves the same way.

The gates exist so the GM symbol dict (for @sfz) and the notation IO surface (for @notation-io) don’t sit in scope for composers who never asked for them.

Core Functions

These are always available (no use needed for some; use "@std" for the printable / convertible surface).

I/O

FunctionSignatureDescription
print(String) -> VoidPrint string with newline
input() -> StringRead a line from stdin

String Operations

FunctionSignatureDescription
str(T) -> StringConvert any value to string
len(String) -> IntString length
len(T[]) -> IntArray length
concat(String, String) -> StringConcatenate strings
concat(T[], T[]) -> T[]Concatenate arrays

str ships with 20+ overloads — Int, Long, Float, Double, Number, String, Bool, Note, Symbol, Bar, Semitone, Cent, Millisecond, Second, Decibel, Array, Sequence, Chord, Section, Song, Tuning, and more.

Arithmetic (prefix-only)

Flow has no infix + - * /. Use the prefix builtins:

FunctionSignatureDescription
add / sub / mul / div(Int, Int) plus Float / Double / Long / Number overloadsSame-type fast paths
neg(Int) -> Int / (Double) -> DoubleUnary negation
idiv(Int, Int) -> IntInteger (floor) division
abs / min / max(Int, Int) / (Double, Double)Standard ops

Math

FunctionSignatureDescription
sin / cos / tan(Double) -> DoubleTrig
sqrt / pow / log(Double) -> DoubleExponential / log
floor / ceil / round(Double) -> IntRounding
pi / tau() -> Doubleπ and 2π

Comparison and Logic

FunctionSignatureDescription
equals / sequals(T, T) -> BoolLoose / strict equality
lt / gt / lte / gte(T, T) -> BoolOrdering
and / or(Bool, Bool) + lazy overloadShort-circuit via Lazy<Bool>
not(Bool) -> BoolLogical NOT
if(Bool, Lazy<T>, Lazy<T>) -> TLazy-branch conditional
eval(Lazy<T>) -> TForce a lazy thunk

Type Conversion

FunctionSignatureDescription
intToDouble / doubleToInt(Int) -> Double / (Double) -> IntNumeric coercion
stringToInt / stringToDouble(String) -> Int / (String) -> DoubleParse — returns Void on failure

Random

FunctionSignatureDescription
?() -> FloatRandom float [0, 1)
??() -> FloatSeeded random float
??set(Int) -> VoidSet the seeded RNG state
??reset() -> VoidReset to initial seeded state

For algorithmic / Markov / Tidal-style randomness, see Generative Music. All stochastic builtins in @patterns / @generative / @improv route through a per-render PRNG registry instead of these legacy globals.

Collections (@collections)

See Collections for the deep-dive.

FunctionSignatureDescription
list(...T) -> T[]Create array from varargs
head / tail / last / initarray operationsCommon destructuring
empty / length / lenpredicates / size
reverse / take / droparray ops
append / prepend / concatarray building
contains(T[], T) -> BoolMembership
map / filter / reduce / each(T[], …) -> …Higher-order ops
range(Int, Int) -> Int[]Integer range [lo, hi)
zip(T[], U[]) -> [T, U][]Pair elements

Dict — 14-op surface

Dict<K, V> is a generic, insertion-order-preserving dictionary. Keys may be Int, Long, Float, String, Symbol, Note, Chord, or tuples of hashables. Construct via:

Dict<Symbol, Int> d = (dict #a 1 #b 2 #c 3)
Dict<Symbol, Int> d2 = (dictTuple <<#a, 1>> <<#b, 2>>)
Open in playground
OpSignatureDescription
get(Dict, K) -> VLookup (errors if missing)
getOr(Dict, K, V) -> VLookup with default
set(Dict, K, V) -> DictInsert / update
remove(Dict, K) -> DictDelete a key
has(Dict, K) -> BoolMembership test
keys / values(Dict) -> ArrayAll keys / values in insertion order
size(Dict) -> IntEntry count
merge(Dict, Dict) -> DictRHS keys win
each / map / filter(Dict, Function)Higher-order ops

Audio (@audio)

See Audio and Synthesis, Effects, and Playback and Export for full coverage. This is a navigation summary.

Buffer creation and inspection

FunctionSignatureNotes
createBuffer(Int frames, Int channels, Int sampleRate) -> Buffer
silence(Double seconds) -> BufferZero-filled buffer
getFrames / getChannels / getSampleRate(Buffer) -> Int
getSample / setSamplesample I/O
fillBuffer / copyBuffer / sliceBufferbuffer mutation / copy
appendBuffers / mix / mixBufferscombiningmix is unity gain; mixBuffers is per-source gain
scaleBuffer / fadeIn / fadeOutshaping

Signal generation

FunctionSignature
createSineTone / createSawTone / createSquareTone / createTriangleTone(Double dur, Double freq, Double amp)
generateSine / generateSaw / generateSquare / generateTriangle(Buffer, OscillatorState, Double freq)
oscillatorRegister a custom wavetable: (String name, Function gen[, Int tableSize]) or (String name, Array table)

createSineTone and friends also accept a Hertz literal: (createSineTone 0.5 440Hz 0.5).

Envelopes

FunctionSignature
createAR(Double attack, Double release, Int sr) -> Envelope
createADSR(Double attack, Double decay, Double sustain, Double release, Int sr) -> Envelope
applyEnvelope(Buffer, Envelope) -> Buffer

Effects

See Effects.

FunctionSignatureNotes
reverb(Buffer, Double decay) + 4-arg overload
lowpass / highpass`(Buffer, DoubleHertz cutoff)`
bandpass`(Buffer, DoubleHertz center, Double
compress / sidechaindynamics processors
delay(Buffer, Double time, Double feedback, Double mix)
gain`(Buffer, DoubleDecibel)`
volume(Buffer, Double)Linear0.5 = half amplitude
pan(Buffer, Double)Stereo pan -1..+1
granular(Buffer, grain, density, jitter[, Symbol windowing])3 overloads — Hann / Gaussian / Tukey windowing
stretch(Buffer, Double factor[, mode, frameSize, hopSize, overlap, transientThreshold, pitchPeriod, windowSize])8-arity prefix-ladder; #vocoder / #psola / #auto
pitchShift`(Buffer, DoubleCent

Playback

FunctionSignatureDescription
play(Buffer) -> Void / (Sequence) -> VoidBlocking
stream(Buffer) -> Void / (Sequence) -> VoidNon-blocking
loop(Buffer) -> Void / (Buffer, Int)Loop
preview(Buffer) -> VoidLow-quality preview
stop() -> VoidStop playback
audioDevices / setAudioDevice / isAudioAvailable

WAV / MIDI I/O

FunctionSignatureNotes
writeWav(String path, Buffer) + bit-depth overloadPath-first
exportWav(Buffer, String path) + bit-depth overloadBuffer-first
loadWav(String path) + semitone / ratio varispeed overloadsIdentity short-circuit at semitones=0 / ratio=1.0
writeMidi(String path, Song)Multi-track Standard MIDI File export

Timeline and Voice (@composition)

FunctionSignatureDescription
setBPM / getBPMtempo control
beatsToFrames / framesToBeatsconversion
createVoice / setVoiceGain / setVoicePan / setVoiceOffsetvoice ops
createTrack / addVoice / setTrackGain / setTrackPan / setTrackOffsettrack ops
renderTrack(Track, Double beats) -> Buffer
setMaxVoices(Int) -> VoidPolyphonic voice-pool size
renderSong(Song, String synth) / (Song, Function customInstr) / (Song, String, Second release)release= named arg controls sustain-pedal tail length

Vocalization

See Vocalization.

FunctionSignatureDescription
sing(String, Note, Double) -> BufferFormant-synthesized vowel / syllable
tts(String) -> BufferExternal TTS → buffer
setTtsCommand(String) -> VoidConfigure TTS command template

Visualization

See Visualization.

FunctionSignatureDescription
visualize(Sequence) -> Void / (Buffer) -> VoidASCII piano-roll / waveform
prettyBuffer(Buffer) -> VoidHeader + 60×11 waveform
bufferHex(Buffer) -> Void / (Buffer, Int, Int) -> VoidHex dump

Notation (@notation)

See Note Streams for the inline | ... | syntax; @notation is the imperative-style API.

FunctionSignatureDescription
createMusicalNote(Note, NoteValue) -> MusicalNote
createRest(NoteValue) -> MusicalNote
createTimeSignature(Int, Int) -> TimeSignature
createMusicalBar / createEmptyMusicalBar(...) -> Bar
createSequence / addBarToSequence(...) -> Sequence
noteToFrequency(Note) -> DoubleA4 = 440
noteValueToBeats / validateBarDuration / getRemainingBeats / wouldFitbar arithmetic

Plus note-value constants WHOLE, HALF, QUARTER, EIGHTH, SIXTEENTH, THIRTYSECOND and time-signature presets TS_4_4, TS_3_4, TS_6_8, TS_2_4, TS_5_4, TS_9_8, TS_12_8.

Bars (@bars)

FunctionSignatureDescription
createBar / createBarWithNote / createBarFromNotes(...) -> Bar
addNoteToBar / tryAddNoteToBarbar mutation
getNoteFromBar / barLengthbar inspection
setTimeSignature / getTimeSignaturebar metadata

Harmony

Always-on (registered as C# builtins).

FunctionSignatureDescription
chordNotes(Chord) -> String[]Notes in chord
chordRoot / chordQuality(Chord) -> StringChord parts
arpeggio(Chord, String) -> Sequence"up", "down", "updown"
scaleNotes(String) -> String[]Scale note names
resolveNumeral(String, String) -> ChordRoman numeral → chord
getSections / sectionSequences(Song) -> String[] / (Section) -> String[]Song introspection

See Chords and Harmony and Chord Progressions.

Transforms (always-on)

See Pattern Transforms for the deep dive.

FunctionSignature
transpose(Sequence, Semitone) / (Sequence, Cent)
invert / retrograde(Sequence) -> Sequence
augment / diminishduration scaling
up / down(Sequence, Int) -> Sequence
repeat(Sequence, Int) / (Sequence, Int, Semitone)
concat(Sequence, Sequence) -> Sequence
crescendo / decrescendo / swellvelocity shaping
ritardando / accelerandotempo feel
fermata / trill / tremoloembellishment
humanize(Sequence, Double) — uniform velocity jitter
humanizeGaussian(Sequence, Double, Int seed) — Box-Muller, seeded, voice-block-aware
legato(Sequence, Double) — duration overlap

Composition

Loaded via @composition.

FunctionSignatureDescription
euclidean(Int, Int, Note) + swing / humanize overloadsBjorklund rhythm
vary(Sequence, Double) + typed / seeded / diatonic overloadsStochastic mutation
polyrhythm(Sequence, Sequence) / (…, Int)LCM overlay
tempoRamp(Sequence, Double, Double) / (…, String)Rendered tempo interpolation
renderSequenceToVoices / renderBarToVoices / renderBarAtBeat / renderBarAtTimelow-level voice rendering

Pattern Combinators (@patterns)

13 Tidal-style combinators on Sequence. Cycle unit is bars; transform-arg combinators are lambda-required; degenerate inputs return input + advisory (never throws). See Generative Music for full coverage.

CombinatorSignature
every(Int n, Function cb, Sequence seq) -> Sequence
fast / slow(Sequence, Double factor) -> Sequence
chunk(Int n, Function cb, Sequence seq) -> Sequence
phase(Double offset, Sequence seq) -> Sequence
rev / palindrome(Sequence) -> Sequence
iter(Int n, Sequence seq) -> Sequence
jux / superimpose(Function cb, Sequence seq) -> Sequence
sometimes(Double prob, Function cb, Sequence seq) + default-prob overload
degrade(Sequence) -> Sequence (fixed 50% drop)
sparseSeq(Double prob, Sequence seq) -> Sequence

Generative (@generative)

Markov, L-system, cellular automata, chaos maps. See Generative Music.

FunctionSignature
markov / markovTrain / markovGenerate / markovEqualMarkov chains, train+generate split, structural compare
lsystem / lsystemModel / lsystemGenerate / lsystemToSequence / lsystemEqualL-systems
cellular / cellularSeeded / life1D + 2D cellular automata
lorenz / logistic / quantizeToScaleChaos maps + scale bridge

Improv (@improv)

See Generative Music.

FunctionSignature
jam6 arity overloads of jam(over[, style, length, key, seed, order]) -> Sequence
registerStyle(Symbol name, Dict pack) -> Void
listStyles() -> Array[Symbol]

Shipped style packs: #jazz, #blues, #classical (composer-editable Flow files under flow-lang/improv/styles/).

SFZ Orchestral Sampler (@sfz)

Opt-in via use "@sfz" (flips the SfzEnabled runtime gate). See Audio and Synthesis.

FunctionSignatureDescription
loadSfz(Symbol) -> SfzResolves against the 20-entry GM dict + sfz_root config
loadSfz(String path) -> SfzAbsolute path bypass

After loading, dispatch via renderSong song "sampler:NAME". The dict ships #violin, #viola, #cello, #contrabass, #flute, #oboe, #clarinet, #bassoon, #trumpet, #horn, #trombone, #tuba, #piano, #harp, #timpani, #drums, plus 4 placeholders for instruments not in VSCO-CE (#choir, #guitar, #harpsichord, #celeste) which point composers at the absolute-path overload.

Notation IO (@notation-io)

Opt-in via use "@notation-io" (flips the NotationIoEnabled runtime gate). See Playback and Export.

FunctionSignatureNotes
writeMusicXML(String path, Song) -> VoidMusicXML 3.1 partwise, MuseScore-compatible
writeLilyPond(String path, Song) -> VoidLilyPond 2.24+ text
abc(String source) -> Section / (String source) -> Array[Section]ABC 2.1 subset + abc2midi extensions; multi-tune X:1/X:2 returns an array
mml(String source) -> SequencePC-98 MML common core

Distinct from @notation, which provides the musical-notation primitives (bar/sequence construction).

Test Framework (@test)

Phase 35 test framework. See tests/test_test_library.flow for the legacy pure-Flow assertion API as well.

FunctionSignatureNotes
test(String name, Lazy<Void> body) -> VoidWrap body with lazy(...) so it’s deferred until the runner forces it
assert(Bool) -> Void
assertEq(T, T) -> Void
assertNotesMatch(Sequence, Sequence) -> VoidStructural sequence compare
assertBytesEqual(Buffer, Buffer) -> VoidByte-identical buffer compare
assertWithinDb(Buffer, Buffer, Decibel tolerance) -> VoidPerceptual tolerance for things that legitimately change bytes

Legacy procs assertTrue, assertEqual, runTest(String, Function), and summary remain available for older test suites.

See Also