-
Notifications
You must be signed in to change notification settings - Fork 1
/
hof.go
446 lines (369 loc) · 9.32 KB
/
hof.go
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package ginsu
// Copyright 2020 streamz
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// hof.go Higher Order Functions for golang
import (
"errors"
"fmt"
"reflect"
)
// T container for a type
//
// Used to wrap any builtin or user type:
// T{[]int{1, 2, 3}}
// To extract the value out of the container apply the appropriate type assertion:
// t := T{[]int{1, 2, 3}}
// i := t.I.([]int)
type T struct {
I interface{}
}
// F container for a function, type alias for T
//
// Used to wrap a func variable or literal:
// F{func(p point) bool {
// return (p.x == p.y)
// }}
type F = T
type _K = []reflect.Kind
type _R struct {
I _K
O _K
}
type _U = struct{}
type _V = []reflect.Value
var none = T{}
var invalidfn = "fn is of type %T it is not a function"
var invalidnin = "invalid arity expected %d in params, received %d"
var invalidnout = "invalid arity expected %d params, received %d"
var invalidkin = "invalid input kind param num %d expected %d, received %d"
var invalidkout = "invalid output kind param num %d expected %d, received %d"
var invalidslice = "invalid slice received %T"
// Apply captures args, applies F to T and returns T when result invoked
// f := Apply(F{func(a, b int) int {
// return a + B
// }}, T{1}, T{2})
// r := f()
// // r == 3
// returns func()T || error
func Apply(fn F, args ...T) (func()T, error) {
return fn.apply(args...)
}
// AsyncRepeat executes a Nullary F in a goroutine until result is executed"
// cancel := AsyncRepeat(F{func() {
// // do something
// }}, func() {
// // defered do something
// })
// // Stop doing something
// cancel()
func AsyncRepeat(fn F, defered func()) func() {
c := make(chan _U)
cancel := func() {
close(c)
}
go fn.until(c, defered)
return cancel
}
// Compare T Generic
// Compare two type T by applying a binary function:
// Compare(T{[]int{1, 2, 3}}, T{[]int{1, 2, 3}}, F{func(i0 int, i1 int) bool {
// return i0 == i1
// }})
// returns (true || false) || error
func Compare(this, that T, fn F) (bool, error) {
return this.compare(that, fn)
}
// Filter T Generic
// Filter a slice by items that match the given predicate:
// Filter(T{[]int{1, 2, 3}}, F{func(i int) bool {
// return i % 2 == 0
// }})
// returns T{[]int} || error
func Filter(t T, fn F) (T, error) {
return t.filter(fn, false)
}
// FilterNot T Generic
// Filter a slice by items that do NOT match the given predicate:
// FilterNot(T{[]int{1, 2, 3}}, F{func(i int) bool {
// return i % 2 == 0
// }})
// returns T{[]int} || error
func FilterNot(t T, fn F) (T, error) {
return t.filter(fn, true)
}
// ForAll T Generic
// Return true if ALL items match the given predicate:
// ForAll(T{[]int{1, 2, 3}}, F{func(i int) bool {
// return i < 10
// }})
// returns (true || false) || error
func ForAll(t T, fn F) (bool, error) {
return t.foranyall(fn, true)
}
// ForAny T Generic
// Return true if ANY item match the given predicate:
// ForAny(T{[]int{1, 2, 3}}, F{func(i int) bool {
// return i == 2
// }})
// returns (true || false) || error
func ForAny(t T, fn F) (bool, error) {
return t.foranyall(fn, false)
}
// ForEach T Generic
// Apply the fn to T:
// ForEach(T{[]int{1, 2, 3}}, F{func(i int) {
// fmt.PrintF("%d\n", i)
// }})
// returns error
func ForEach(t T, fn F) error {
return t.foreach(fn)
}
// Map T Generic
// Apply the transform fn to A and return a new slice:
// Map(A{[]int{1, 2, 3}}, F{Itoa})
// returns B || error
func Map(t T, fn F) (T, error) {
return t.fmap(fn)
}
// Reduce T Generic
// Reduces the elements of T by applying fn as an associative binary operator
// Reduce(T{0}}, T{[]int{1, 2, 3}}, F{func(acc int, i int) int {
// return acc + i
// }})
// returns a single reduced element of wrapped slice in T{} || error
func Reduce(initial, t T, fn F) (T, error) {
return t.reduce(initial)(fn)
}
func kindOf(t reflect.Type) reflect.Kind {
return t.Elem().Kind()
}
func assertslice(t reflect.Type) error {
if t.Kind() != reflect.Slice {
return fmt.Errorf(invalidslice, t)
}
return nil
}
func (fn F) assert(r _R) error {
return fn.assertio(r, true)
}
func (fn F) assertio(r _R, io bool) error {
t := reflect.ValueOf(fn.I).Type()
if t.Kind() != reflect.Func {
return fmt.Errorf(invalidfn, t)
}
nin := t.NumIn()
enin := len(r.I)
if nin != enin {
return fmt.Errorf(invalidnin, enin, nin)
}
nout := t.NumOut()
if io {
enout := len(r.O)
if nout != enout {
return fmt.Errorf(invalidnout, enout, nout)
}
}
for i := 0; i < nin; i++ {
in := t.In(i).Kind()
expect := r.I[i]
if in != expect {
return fmt.Errorf(invalidkin, i, expect, in)
}
}
if io {
for i := 0; i < nout; i++ {
out := t.Out(i).Kind()
expect := r.O[i]
if out != expect {
return fmt.Errorf(invalidkout, i, expect, out)
}
}
}
return nil
}
func (fn F) apply(args ...T) (func()T, error) {
// unwrap args
in, _ := T{args}.fmap(F{func(t T) reflect.Value {
return reflect.ValueOf(t.I)
}})
ink, _ := in.fmap(F{func(v reflect.Value) reflect.Kind {
return v.Kind()
}})
f := reflect.ValueOf(fn.I)
t := f.Type()
nout := t.NumOut()
outk := make(_K, nout)
for i := 0; i < nout; i++ {
outk[i] = t.Out(i).Kind()
}
// this check is redundant for out
inkt := ink.I.(_K)
if err := fn.assert(_R{inkt, outk}); err != nil {
return nil, err
}
res := func() T {
inv := in.I.([]reflect.Value)
o := f.Call(inv[:])[0].Interface()
return T{o}
}
return res, nil
}
func (fn F) until(c chan _U, defered func()) {
defer defered()
fn.assert(_R{_K{},_K{}})
f := reflect.ValueOf(fn.I)
running := func(ch chan _U) bool {
select {
case <-ch:
return false
default:
return true
}
}
for running(c) {
f.Call(_V{})
}
}
func (t T) compare(other T, fn F) (bool, error) {
this := reflect.ValueOf(t.I)
that := reflect.ValueOf(other.I)
if err := assertslice(this.Type()); err != nil {
return false, err
}
// assert function arity
k := kindOf(this.Type())
if err := fn.assert(_R{_K{k, k}, _K{reflect.Bool}}); err != nil {
return false, err
}
// compare len of slices
if this.Len() != that.Len() {
return false, nil
}
f := reflect.ValueOf(fn.I)
var p [2]reflect.Value
for i := 0; i < this.Len(); i++ {
p[0] = this.Index(i)
p[1] = that.Index(i)
if !f.Call(p[:])[0].Bool() {
return false, nil
}
}
return true, nil
}
func (t T) filter(fn F, not bool) (T, error) {
this := reflect.ValueOf(t.I)
if err := assertslice(this.Type()); err != nil {
return none, err
}
k := kindOf(this.Type())
if err := fn.assert(_R{_K{k}, _K{reflect.Bool}}); err != nil {
return none, err
}
f := reflect.ValueOf(fn.I)
o := reflect.MakeSlice(this.Type(), 0, this.Len())
var p [1]reflect.Value
for i := 0; i < this.Len(); i++ {
p[0] = this.Index(i)
r := f.Call(p[:])[0].Bool()
if (r && !not) || (!r && not) {
o = reflect.Append(o, this.Index(i))
}
}
return T{o.Interface()}, nil
}
func (t T) foranyall(fn F, all bool) (bool, error) {
this := reflect.ValueOf(t.I)
if err := assertslice(this.Type()); err != nil {
return false, err
}
k := kindOf(this.Type())
if err := fn.assert(_R{_K{k}, _K{reflect.Bool}}); err != nil {
return false, err
}
f := reflect.ValueOf(fn.I)
var p [1]reflect.Value
for i := 0; i < this.Len(); i++ {
p[0] = this.Index(i)
call := f.Call(p[:])[0].Bool()
if all && !call {
return false, nil
} else if !all && call {
return true, nil
}
}
return all, nil
}
func (t T) foreach(fn F) error {
this := reflect.ValueOf(t.I)
if err := assertslice(this.Type()); err != nil {
return err
}
k := kindOf(this.Type())
if err := fn.assert(_R{_K{k}, _K{}}); err != nil {
return err
}
f := reflect.ValueOf(fn.I)
var p [1]reflect.Value
for i := 0; i < this.Len(); i++ {
p[0] = this.Index(i)
f.Call(p[:])
}
return nil
}
func (t T) fmap(fn F) (T, error) {
this := reflect.ValueOf(t.I)
if err := assertslice(this.Type()); err != nil {
return none, err
}
k := kindOf(this.Type())
if err := fn.assertio(_R{_K{k}, _K{}}, false); err != nil {
return none, err
}
f := reflect.ValueOf(fn.I)
v := f.Type().Out(0)
vs := reflect.SliceOf(v)
o := reflect.MakeSlice(vs, 0, this.Len())
var p [1]reflect.Value
for i := 0; i < this.Len(); i++ {
p[0] = this.Index(i)
o = reflect.Append(o, f.Call(p[:])[0])
}
return T{o.Interface()}, nil
}
func (t T) reduce(initial T) func(fn F) (T, error) {
return func(fn F) (T, error) {
this := reflect.ValueOf(t.I)
out := reflect.ValueOf(initial.I)
if err := assertslice(this.Type()); err != nil {
return none, err
}
it := this.Type().Elem().Kind()
ik := out.Kind()
if it != ik {
return T{}, errors.New("Type mismatch")
}
k := kindOf(this.Type())
if err := fn.assert(_R{_K{k, k}, _K{it}}); err != nil {
return none, err
}
var p [2]reflect.Value
f := reflect.ValueOf(fn.I)
for i := 0; i < this.Len(); i++ {
p[0] = out
p[1] = this.Index(i)
out = f.Call(p[:])[0]
}
return T{out.Interface()}, nil
}
}