-
Notifications
You must be signed in to change notification settings - Fork 0
/
transducers.zp
129 lines (117 loc) · 3.19 KB
/
transducers.zp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
; ("sequence" sequence)
; ("educe" educe)
(module "transducers"
(export
(list "transduce" transduce)
(list "compose" compose)
(list "into" into)
(list "filter" filt)
(list "remove" rem)
(list "cat" cat)
(list "map" ma)
(list "mapcat" mapcat)
(list "reduce" red)
(list "take" take)
(list "partition-by" partition-by))
(reduce- (lambda (f init col)
(cond
((list? col) (reduce f init col))
((vector? col) (vector:reduce f init col))
((byte-vector? col) (byte-vector:reduce f init col))
((hash-map? col) (hash:kv-reduce f init col))
(else (error "not a collection: " col)))))
(transduce (case-lambda
((forms f col) (transduce forms f (f) col))
((forms f init col)
(let* ((x (forms f))
(ret (reduce- x init col)))
(x ret)))
((forms f init col rf)
(let* ((x (forms f))
(ret (rf x init col)))
(x ret)))))
(into (case-lambda
((to forms from) (transduce forms += to from))
((to forms from alt) (transduce forms += to from alt))))
(compose (case-lambda
(() id)
((f) f)
((f g)
(case-lambda
(() (f (g)))
((x) (f (g x)))
((x y) (f (g x y)))
((x y z) (f (g x y z)))
(args (begin (write g) (write args) (f (apply g args))))))
(fs
(reduce compose (car fs) (cdr fs)))))
(ma (lambda (f)
(lambda (rf)
(case-lambda
(() (rf))
((res) (rf res))
((res in) (rf res (f in)))))))
(filt (lambda (pred)
(lambda (rf)
(case-lambda
(() (rf))
((res) (rf res))
((res in) (if (pred in) (rf res in) res))))))
(rem (lambda (pred)
(lambda (rf)
(case-lambda
(() (rf))
((res) (rf res))
((res in) (if (not (pred in)) (rf res in) res))))))
(cat (lambda (rf)
(case-lambda
(() (rf))
((res) (rf res))
((res in) (reduce- rf res in)))))
(red (lambda (f)
(lambda (rf)
(case-lambda
(() (rf))
((res) (rf res))
((res in) (rf res (f res in)))))))
(take (lambda (n)
(lambda (rf)
(let ((nv n))
(case-lambda
(() (rf))
((res) (rf res))
((res in)
(let ((n nv))
(begin
(set! nv (sub1 nv))
(if (positive? n) (rf res in) res)))))))))
(mapcat (lambda (f)
(compose (ma f) cat)))
(partition-by (lambda (f)
(lambda (rf)
(let ((a '())
(pv (nil)))
(case-lambda
(() (rf))
((res)
(let ((res (if (null? a)
res
(let ((v a))
(begin
(set! a [])
(rf res v))))))
(rf res)))
((res in)
(let ((pval pv)
(val (f in)))
(if (or (nil? pval) (eq? val pval))
(begin
(set! pv in)
(set! a (++ a in))
res)
(let* ((v a)
(ret (rf res v)))
(begin
(set! pv in)
(set! a (list in))
ret)))))))))))