| 1 |
// run |
| 2 |
|
| 3 |
// Copyright 2021 The Go Authors. All rights reserved. |
| 4 |
// Use of this source code is governed by a BSD-style |
| 5 |
// license that can be found in the LICENSE file. |
| 6 |
|
| 7 |
package main |
| 8 |
|
| 9 |
type Iterator[T any] interface { |
| 10 |
Iterate(fn func(T) bool) |
| 11 |
} |
| 12 |
|
| 13 |
type IteratorFunc[T any] func(fn func(T) bool) |
| 14 |
|
| 15 |
func (f IteratorFunc[T]) Iterate(fn func(T) bool) { |
| 16 |
f(fn) |
| 17 |
} |
| 18 |
|
| 19 |
type Stream[T any] struct { |
| 20 |
it Iterator[T] |
| 21 |
} |
| 22 |
|
| 23 |
func (s Stream[T]) Iterate(fn func(T) bool) { |
| 24 |
if s.it == nil { |
| 25 |
return |
| 26 |
} |
| 27 |
s.it.Iterate(fn) |
| 28 |
} |
| 29 |
|
| 30 |
func FromIterator[T any](it Iterator[T]) Stream[T] { |
| 31 |
return Stream[T]{it: it} |
| 32 |
} |
| 33 |
|
| 34 |
func (s Stream[T]) DropWhile(fn func(T) bool) Stream[T] { |
| 35 |
return Pipe[T, T](s, func(t T) (T, bool) { |
| 36 |
return t, true |
| 37 |
}) |
| 38 |
} |
| 39 |
|
| 40 |
func Pipe[T, R any](s Stream[T], op func(d T) (R, bool)) Stream[R] { |
| 41 |
it := func(fn func(R) bool) { |
| 42 |
// XXX Not getting the closure right when converting to interface. |
| 43 |
// s.it.Iterate(func(t T) bool { |
| 44 |
// r, ok := op(t) |
| 45 |
// if !ok { |
| 46 |
// return true |
| 47 |
// } |
| 48 |
|
| 49 |
// return fn(r) |
| 50 |
// }) |
| 51 |
} |
| 52 |
|
| 53 |
return FromIterator[R](IteratorFunc[R](it)) |
| 54 |
} |
| 55 |
|
| 56 |
func Reduce[T, U any](s Stream[T], identity U, acc func(U, T) U) (r U) { |
| 57 |
r = identity |
| 58 |
s.Iterate(func(t T) bool { |
| 59 |
r = acc(r, t) |
| 60 |
return true |
| 61 |
}) |
| 62 |
|
| 63 |
return r |
| 64 |
} |
| 65 |
|
| 66 |
type myIterator struct { |
| 67 |
} |
| 68 |
|
| 69 |
func (myIterator) Iterate(fn func(int) bool) { |
| 70 |
} |
| 71 |
|
| 72 |
func main() { |
| 73 |
s := Stream[int]{} |
| 74 |
s.it = myIterator{} |
| 75 |
s = s.DropWhile(func(i int) bool { |
| 76 |
return false |
| 77 |
}) |
| 78 |
Reduce(s, nil, func(acc []int, e int) []int { |
| 79 |
return append(acc, e) |
| 80 |
}) |
| 81 |
} |