-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path056_map.go
50 lines (43 loc) · 826 Bytes
/
056_map.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
package main
import "fmt"
func Map[T any](s any, f func(T) T) (r []T) {
switch s := s.(type) {
case interface{ Range(func(int, T)) }:
s.Range(func(i int, v T) {
r = append(r, f(v))
})
}
return
}
func DoMap[T ~int | ~float32](s any) {
r := Map(s, func(v T) T {
return v * 2
})
fmt.Printf("Map(%v, func()): %v\n", s, r)
}
type NFunc[T any] func(int) (T, bool)
func (f NFunc[T]) Range(p func(i int, v T)) {
for i := 0; ; i++ {
if r, ok := f(i); ok {
p(i, r)
} else {
break
}
}
}
func Limit[T any](i, j int, f NFunc[T]) NFunc[T] {
return func(x int) (r T, ok bool) {
if i <= x && x <= j {
r, ok = f(x)
}
return
}
}
func main() {
DoMap[int](Limit(0, 4, func(x int) (int, bool) {
return x, true
}))
DoMap[float32](func(x int) (float32, bool) {
return float32(x), (x < 5)
})
}