Skip to content

ST Combinators

ST is a functor. Calling a stream as a function dispatches on the argument type:

ArgumentResult
Another STConcatenate
No-arg function (combinator)Apply combinator to self
Any valueAppend singleton

The combinator form — stream (st.map f) — applies st.map f in-place, returning a transformed stream.

Transform each element:

(st 1 2 3) (st.map (x: x * 10))
# → ST [10 20 30]

Equivalent to map-c f stream.

Keep elements matching a predicate:

(st 1 2 3 4 5) (st.filter (x: x > 3))
# → ST [4 5]

Equivalent to filtering with when-c.

Apply multiple combinators in sequence:

flowchart LR
  s["ST [1,2,3,4]"]
  m["st.map ×2\n→ [2,4,6,8]"]
  f["st.filter >4\n→ [6,8]"]
  out["ST [6,8]"]
  s --> m --> f --> out
(st 1 2 3 4) (st.map (x: x * 2)) (st.filter (x: x > 4))
# → ST [6 8]

Map and flatten — each element can produce zero or more outputs:

(st 1 2 3) (st.flatMap (x: st x x))
# → ST [1 1 2 2 3 3]

Running fold that emits the accumulator at every step, including the initial value:

(st 1 2 3 4) (st.scanl (acc: x: acc + x) 0)
# → ST [0 1 3 6 10]
# initial=0, then 0+1=1, 1+2=3, 3+3=6, 6+4=10

scanl emits the initial accumulator first, then one value per element — so N elements produce N+1 outputs.

MethodDescription
.toListEvaluate stream to a Nix list
.filter predFilter elements (same as st.filter combinator)
.flatMap fMap and flatten
.rightFilter to elements with a right field
.leftFilter to elements with a left field
st.fromList listConvert Nix list to stream
st.flatten stream-of-streamsFlatten one level
fields "key"Extract a field from each element, flatten ST values
Contribute Community Sponsor