AtlatestRepositorysigil-transducers
1# sigil-transducers
2
3Composable transducer library for Sigil. Provides polymorphic sequence operations and transducer pipelines that work across lists, vectors, arrays, and dicts.
4
5## Installation
6
7Add to your `package.sgl` dependencies:
8
9```scheme
10(from-git url: "codeberg:sigil/sigil-transducers")
11```
13## Usage
15### Polymorphic Operations
17When imported, `(sigil seq)` provides polymorphic versions of common operations that work on any collection type:
19```scheme
20(import (sigil seq))
22(map square '(1 2 3)) ; => (1 4 9)
23(map square #(1 2 3)) ; => #(1 4 9)
24(filter even? '(1 2 3 4)) ; => (2 4)
25(filter even? #(1 2 3 4)) ; => #(2 4)
26(fold + 0 '(1 2 3 4)) ; => 10
27(any even? '(1 3 4 5)) ; => #t
28(every even? '(2 4 6)) ; => #t
29(find even? '(1 3 4 5)) ; => 4
30```
32### Transducers
34Transducers are composable transformation pipelines that separate *what* to transform from *how* to iterate:
36```scheme
37(import (sigil seq))
39(define xform
40 (comp (filtering even?)
41 (mapping square)
42 (taking 5)))
44(transduce xform conj '() (iota 100)) ; => (0 4 16 36 64)
45```
47### Transducer Constructors
49- `(mapping f)` - Transform each element by applying `f`
50- `(filtering pred)` - Keep only elements satisfying `pred`
51- `(taking n)` - Take at most `n` elements, then stop
52- `(dropping n)` - Skip the first `n` elements
53- `(taking-while pred)` - Take elements while `pred` is true
54- `(dropping-while pred)` - Drop elements while `pred` is true
55- `cat` - Flatten one level of nesting
56- `(mapcat f)` - Map then concatenate
58### Composition
60Compose transducers left-to-right with `comp`:
62```scheme
63(comp (filtering even?) (mapping square) (taking 3))
64```
66### Execution
68- `(transduce xform rf init coll)` - Apply transducer `xform` with reducing function `rf`, initial value `init`, over collection `coll`
69- `(into to xform from)` - Transform and collect into a collection of the same type as `to`
70- `(sequence xform coll)` - Transform a collection, preserving its type
72### Reducers
74- `conj` - Build lists (via cons)
75- `conj-vec` - Build vectors (builds list, convert with `into`)
76- `conj-dict` - Build dicts from `(key . value)` pairs
78### Stream Processing
80Transducers also work for processing channel message streams:
82```scheme
83(import (sigil seq)
84 (sigil channels)
85 (sigil async))
87(define log-xform
88 (comp (filtering (lambda (msg) (equal? (dict-ref msg level:) "error")))
89 (mapping (lambda (msg) (dict-ref msg text:)))))
91(with-async
92 (go (for-each (lambda (msg) (channel-send logs msg)) messages)
93 (channel-close! logs))
94 (go (for-channel (msg logs)
95 (let ((xrf (log-xform (lambda (acc x) (println "ERROR: ~a" x) acc))))
96 (xrf #f msg)))))
97```
99## License
101BSD-3-Clause