luminyra
Guides

Lazy sequences

Chain filtering, mapping, deduplication, and aggregation with Seq and pull elements on demand.

Build a pipeline

From wraps a slice, and FromSeq accepts an existing Go iterator. Seq.Filter and Seq.Map describe transformations. Building a chain defers reading orders, so you can define multiple results from the same sequence of paid orders.

coll/examples/slices/main.go
// A Seq is lazy: each step runs only when Collect or a range loop pulls
// values. Map is a Go 1.27 generic method, so the chain can turn orders
// into ints or strings.
paid := coll.From(orders).Filter(isPaid)

ids := paid.Map(func(o order) int { return o.ID }).Collect()
total := paid.Fold(0, func(sum int, o order) int { return sum + o.Amount })
customers := paid.UniqBy(func(o order) string { return o.Customer }).
	Map(func(o order) string { return o.Customer }).
	Collect()
View on GitHub

Consume a sequence

Seq.Collect produces a slice, and Seq.Fold combines elements into a single value. The example runs these separately and uses Seq.UniqBy to deduplicate by customer before collecting names. The slice-backed sequence in the example supports repeated iteration. An external iterator's implementation determines whether it can be iterated again.

To take only the first few items, use Seq.Take or exit a range loop early.

coll/example_test.go
isEven := func(n int) bool { return n%2 == 0 }

labels := coll.Of(1, 2, 3, 4, 5, 6).Filter(isEven).Map(strconv.Itoa).Collect()
fmt.Println(labels)
Expected output
[2 4 6]
View on GitHub

On this page