Documentation ¶
Overview ¶
Package iter brings generic Iterator support to Go, inspired by Rust's std::iter::Iterator.
Example ¶
isEven := func(n int) bool { return n%2 == 0 } add := func(a, b int) int { return a + b } sum, ok := CountUpBy(0, 3). // 0, 3, 6, 9, 12, ... Filter(isEven). // 0, 6, 12, 18, ... Take(5). // 0, 6, 12, 18, 24 Reduce(add) // 60 fmt.Println(sum, ok)
Output: 60 true
Index ¶
- func Fold[S, E any](iter Iterator[E], initial S, fn FoldFunc[S, E]) S
- func Max[E constraints.Ordered](iter Iterator[E]) (max E, ok bool)
- func MaxByKey[E any, K constraints.Ordered](iter Iterator[E], fn KeyFunc[E, K]) (E, bool)
- func Min[E constraints.Ordered](iter Iterator[E]) (min E, ok bool)
- func MinByKey[E any, K constraints.Ordered](iter Iterator[E], fn KeyFunc[E, K]) (E, bool)
- func Product[N Number](iter Iterator[N]) (product N)
- func Sum[N Number](iter Iterator[N]) (sum N)
- func TryFold[S, E any](iter Iterator[E], initial S, fn TryFoldFunc[S, E]) (S, error)
- type CompareFunc
- type Core
- type CoreFunc
- type Equality
- type FilterMapFunc
- type FlatMapFunc
- type FoldFunc
- type Iterator
- func CountDownBy[I constraints.Integer](start, step I) Iterator[I]
- func CountUpBy[I constraints.Integer](start, step I) Iterator[I]
- func Empty[E any]() Iterator[E]
- func Enumerate[E any](iter Iterator[E]) Iterator[Pair[int, E]]
- func FilterMap[A, B any](iter Iterator[A], fn FilterMapFunc[A, B]) Iterator[B]
- func FlatMap[A, B any](iter Iterator[A], fn FlatMapFunc[A, B]) Iterator[B]
- func FromBytesScanner(sc *bufio.Scanner) Iterator[[]byte]
- func FromChan[E any](c <-chan E) Iterator[E]
- func FromCore[E any](core Core[E]) Iterator[E]
- func FromCoreFunc[E any](fn CoreFunc[E]) Iterator[E]
- func FromGenerator[E any](gen *generator.Generator[E]) Iterator[E]
- func FromGeneratorFunc[E any](genFn func(yield func(E))) Iterator[E]
- func FromItems[E any](items ...E) Iterator[E]
- func FromSlice[E any](s []E) Iterator[E]
- func FromStringScanner(sc *bufio.Scanner) Iterator[string]
- func Map[A, B any](iter Iterator[A], fn MapFunc[A, B]) Iterator[B]
- func MapWhile[A, B any](iter Iterator[A], fn FilterMapFunc[A, B]) Iterator[B]
- func RangeBy[I constraints.Integer](start, end, step I) Iterator[I]
- func Scan[S, A, B any](iter Iterator[A], initial S, fn ScanFunc[S, A, B]) Iterator[B]
- func Zip[E1, E2 any](a Iterator[E1], b Iterator[E2]) Iterator[Pair[E1, E2]]
- func (iter Iterator[_]) AdvanceBy(n uint) (ct uint, ok bool)
- func (iter Iterator[E]) All(pred Predicate[E]) bool
- func (iter Iterator[E]) Any(pred Predicate[E]) bool
- func (iter Iterator[E]) Chain(iters ...Iterator[E]) Iterator[E]
- func (iter Iterator[E]) Compare(other Iterator[E], fn CompareFunc[E]) Equality
- func (iter Iterator[_]) Count() (ct uint)
- func (iter Iterator[E]) Filter(pred Predicate[E]) Iterator[E]
- func (iter Iterator[E]) Find(pred Predicate[E]) (match E, ok bool)
- func (iter Iterator[E]) ForEach(fn func(E))
- func (iter Iterator[E]) Fuse() Iterator[E]
- func (iter Iterator[E]) Inspect(fn func(E)) Iterator[E]
- func (iter Iterator[E]) Intersperse(sep E) Iterator[E]
- func (iter Iterator[E]) IntersperseWith(sepFn func() E) Iterator[E]
- func (iter Iterator[E]) Last() (last E, ok bool)
- func (iter Iterator[E]) MaxBy(fn LessFunc[E]) (E, bool)
- func (iter Iterator[E]) MinBy(fn LessFunc[E]) (min E, ok bool)
- func (iter Iterator[E]) Next() (next E, ok bool)
- func (iter Iterator[E]) Nth(n uint) (nth E, ok bool)
- func (iter Iterator[E]) Partition(pred Predicate[E]) (trues []E, falses []E)
- func (iter Iterator[E]) Peekable() PeekIterator[E]
- func (iter Iterator[E]) Position(pred Predicate[E]) (idx uint, ok bool)
- func (iter Iterator[E]) Reduce(fn ReduceFunc[E]) (result E, ok bool)
- func (iter Iterator[E]) Skip(n uint) Iterator[E]
- func (iter Iterator[E]) SkipWhile(pred Predicate[E]) Iterator[E]
- func (iter Iterator[E]) StepBy(n uint) Iterator[E]
- func (iter Iterator[E]) Take(n uint) Iterator[E]
- func (iter Iterator[E]) TakeWhile(pred Predicate[E]) Iterator[E]
- func (iter Iterator[E]) ToChan() (ch <-chan E, cancel context.CancelFunc)
- func (iter Iterator[E]) ToChanWithContext(ctx context.Context) (ch <-chan E, cancel context.CancelFunc)
- func (iter Iterator[E]) ToSlice() []E
- func (iter Iterator[E]) TryFind(pred TryPredicate[E]) (match E, ok bool, err error)
- func (iter Iterator[E]) TryForEach(fn func(E) error) error
- func (iter Iterator[E]) TryReduce(fn TryReduceFunc[E]) (result E, ok bool, err error)
- type KeyFunc
- type LessFunc
- type MapFunc
- type Number
- type Pair
- type PeekCore
- type PeekIterator
- type Predicate
- type ReduceFunc
- type ScanFunc
- type TryFoldFunc
- type TryPredicate
- type TryReduceFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Fold ¶
Fold applies an accumulator on an Iterator's elements, reducing it to a final resulting value. Fold takes an Iterator, an initial value for the accumulator, and a FoldFunc that is applied to the current value of the accumulator and the next element of the Iterator. After all elements of the iterator are consumed, the final accumulator value is returned.
Iterator.Reduce is a specialization of Fold, using the first element of the iterator as the initial state.
Example ¶
s := Fold( FromItems(1, 2, 3), 0, func(s int, el int) int { return s + el }) fmt.Println(s)
Output: 6
func Max ¶
func Max[E constraints.Ordered](iter Iterator[E]) (max E, ok bool)
Max consumes the provided Iterator, returning the maximum value emitted. The ok value will be false if the iterator is empty.
func MaxByKey ¶
MaxByKey consumes the provided Iterator, returning the maximum value described by the value returned by the specified KeyFunc.
func Min ¶
func Min[E constraints.Ordered](iter Iterator[E]) (min E, ok bool)
Min consumes the provided Iterator, returning the minimum value emitted. The ok value will be false if the iterator is empty.
func MinByKey ¶
MinByKey consumes the provided Iterator, returning the minimum value described by the value returned by the specified KeyFunc.
func Product ¶
Product computes the product (multiplication) of the elements of an iterator. An empty iterator returns the zero value of the type.
Example ¶
i := FromItems(-1, -2, -3) fmt.Println(Product(i))
Output: -6
func Sum ¶
Sum computes the sum (addition) of the elements of an iterator. An empty iterator returns the zero value of the type.
Example ¶
i := FromItems(1, 2, 3) fmt.Println(Sum(i))
Output: 6
func TryFold ¶
func TryFold[S, E any](iter Iterator[E], initial S, fn TryFoldFunc[S, E]) (S, error)
TryFold is the same as Fold, but takes a TryFoldFunc which allows for fallible accumulation. The first error results in this function short-circuiting, returning the zero value for the accumulator state and the error.
Types ¶
type CompareFunc ¶
CompareFunc is a function that compares two values, returning their relative Equality value.
type Core ¶
type Core[E any] interface { // Next advances the iterator and returns the next element. The ok value is // set to false when the iteration is finished. Individual iterator // implementations may choose to resume iteration, and so calling Next // again may or may not eventually start returning values again at some // point. Next() (next E, ok bool) }
Core represent the basic functionality of an Iterator that enables all other features exposed on the type. Custom implementations typically only need to implement a Core (or PeekCore).
type CoreFunc ¶
CoreFunc is a convenience type for implementing Core for a function that matches the signature of Core.Next.
type Equality ¶
type Equality int8
Equality is an enum type describing the (in)equality of two values
const ( // LessThan indicates that the left-hand value is less than the right-hand // value LessThan Equality = -1 // Equal indicates that the left-hand value is equal to the right-hand // value Equal Equality = 0 // GreaterThan indicates that the left-hand value is greater than the // right-hand value GreaterThan Equality = 1 )
func Compare ¶
func Compare[O constraints.Ordered](a, b Iterator[O]) Equality
Compare lexicographically compares two iterators element-by-element, returning their relative Equality value. For element types that do not satisfy constraints.Ordered, Iterator.Compare or CompareByKey can be used instead.
Example ¶
a := FromItems(1, 2, 3) b := FromItems(1, 2, 4) fmt.Println(Compare(a, b))
Output: LessThan
func CompareByKey ¶
CompareByKey lexicographically compares two iterators element-by-element based off the Equality of the values returned by the provided KeyFunc.
type FilterMapFunc ¶
FilterMapFunc converts a value of type A into B, returning ok as true if the value should be emitted.
type FlatMapFunc ¶
A FlatMapFunc is a MapFunc that emits an Iterator instead as its output value.
type FoldFunc ¶
type FoldFunc[S, T any] func(state S, value T) S
A FoldFunc is an accumulator function takes the current state and the next value, and returns a new version of the state.
type Iterator ¶
type Iterator[E any] struct { // contains filtered or unexported fields }
An Iterator allows for performing streaming operations against elements of a collection or other source of data. At its most fundamental, an Iterator is defined by Core.Next, with all other functionality layered upon it. Custom implementations need only implement Core, using FromCore to expose the rest of the Iterator functionality.
func CountDownBy ¶
func CountDownBy[I constraints.Integer](start, step I) Iterator[I]
CountDownBy returns an unbounded Iterator beginning (inclusively) at the provided start value, and decrements by the provided step. For an iterator that terminates, use RangeBy instead.
func CountUpBy ¶
func CountUpBy[I constraints.Integer](start, step I) Iterator[I]
CountUpBy returns an unbounded Iterator beginning (inclusively) at the provided start value, and incrementing by the provided step. For an iterator that terminates, use RangeBy instead.
func Empty ¶
Empty returns an Iterator that is already finished, never returning an element.
Example ¶
i := Empty[int]() _, ok := i.Next() fmt.Println(ok)
Output: false
func Enumerate ¶
Enumerate zips the elements of the provided Iterator with a zero-indexed counter of each element.
func FilterMap ¶
func FilterMap[A, B any](iter Iterator[A], fn FilterMapFunc[A, B]) Iterator[B]
FilterMap returns an iterator that both filters and maps. The returned iterator yields only yields value for which the supplied FilterMapFunc returns (value, true).
Example ¶
sl := FilterMap( FromItems(0, 1, 2, 12), func(n int) (string, bool) { return fmt.Sprintf("%x", n), n%2 == 0 }).ToSlice() fmt.Println(sl)
Output: [0 2 c]
func FlatMap ¶
func FlatMap[A, B any](iter Iterator[A], fn FlatMapFunc[A, B]) Iterator[B]
FlatMap creates an iterator that works similar to Map, but flattens Iterators.
Map is very useful, but only when the MapFunc produces values. If it produces an iterator instead, there's an extra layer of indirection. FlatMap removes that extra layer internally.
Example ¶
sl := FlatMap( FromItems(1, 2, 3), func(n int) Iterator[int] { return RangeBy(0, n, 1) }).ToSlice() fmt.Println(sl)
Output: [0 0 1 0 1 2]
func FromBytesScanner ¶
FromBytesScanner converts a bufio.Scanner into an Iterator, returning a copy of the []byte emitted by bufio.Scanner.Bytes. Note that the iterator does not produce errors, which would need to be independently checked on the bufio.Scanner after execution.
func FromChan ¶
FromChan converts the provided channel into an Iterator. Most methods on the Iterator will block until the channel can be received from, and possibly will not terminate until the channel is empty and closed.
Example ¶
ch := make(chan int, 3) ch <- 1 ch <- 2 ch <- 3 close(ch) chars := FromChan(ch).ToSlice() fmt.Println(chars)
Output: [1 2 3]
func FromCoreFunc ¶
FromCoreFunc creates an Iterator directly from a CoreFunc.
Example ¶
a, b := 1, 1 fib := FromCoreFunc(func() (int, bool) { out := a a, b = b, a+b return out, true }) fmt.Println(fib.Take(5).ToSlice())
Output: [1 1 2 3 5]
func FromGenerator ¶ added in v0.1.1
FromGenerator creates an Iterator from a generator.Generator.
func FromGeneratorFunc ¶ added in v0.1.1
FromGeneratorFunc creates a generator-based Iterator. This function is equivalent to calling generator.New, then FromGenerator. If the generator will not be exhausted or if it's infinite, FromGenerator should be used instead so that resources can be released via Generator.Close.
func FromStringScanner ¶
FromStringScanner converts a bufio.Scanner into an Iterator, returning the strings emitted by bufio.Scanner.Text. Note that the iterator does not produce errors, which would need to be independently checked on the bufio.Scanner after execution.
func Map ¶
Map converts an Iterator of one type, converting it into an Iterator of another, using the provided MapFunc.
func MapWhile ¶
func MapWhile[A, B any](iter Iterator[A], fn FilterMapFunc[A, B]) Iterator[B]
MapWhile behaves like Map, but will stop emitting values if the provided FilterMapFunc returns false.
func RangeBy ¶
func RangeBy[I constraints.Integer](start, end, step I) Iterator[I]
RangeBy returns an Iterator that begins (inclusively) at the provided start value, approaches the end value by the provided step, and terminates when the end value is reached or passed (exclusive).
func Scan ¶
Scan behaves similar to Fold and MapWhile, but maintains internal state and produces a new Iterator. A pointer to the initial state is passed to the provided ScanFunc for each element on the Iterator. This state can be mutated within the ScanFunc to share state between iterations.
func Zip ¶
Zip merges two Iterator into a single iterator producing Pair of the values emitted by the original iterators in lock-step. The returned iterator is finished if either of the parent iterators completes.
func (Iterator[_]) AdvanceBy ¶
AdvanceBy will skip up to n elements by calling Iterator.Next up to n times or until ok is false. If the iterator has less than n items, the returned ct will be the number of elements skipped with the ok being false. Otherwise, ct will equal n and ok will be true.
func (Iterator[E]) All ¶
All returns true if all elements of the Iterator match the provided Predicate.
func (Iterator[E]) Any ¶
Any returns true if at least one element of the Iterator matches the provided Predicate.
func (Iterator[E]) Chain ¶
Chain returns a new Iterator which will first iterate over values from the original iter and then over values from the subsequent iterators in order.
Example ¶
sl := FromItems(0, 1). Chain(FromItems(2, 3)). ToSlice() fmt.Println(sl)
Output: [0 1 2 3]
func (Iterator[E]) Compare ¶
func (iter Iterator[E]) Compare(other Iterator[E], fn CompareFunc[E]) Equality
Compare lexicographically compares two iterators element-by-element via the provided CompareFunc, returning their relative Equality value. If the element type satisfies constraints.Ordered, Compare can be used instead.
func (Iterator[_]) Count ¶
Count calls Iterator.Next repeatedly until the first time ok is false, returning the number of elements it saw.
func (Iterator[E]) Filter ¶
Filter returns a new iterator that filters elements matching the provided Predicate.
Example ¶
i := FromItems(0, 1, 2, 3, 4, 5).Filter(func(el int) bool { return el%2 == 0 }) fmt.Println(i.ToSlice())
Output: [0 2 4]
func (Iterator[E]) Find ¶
Find returns the first element of the Iterator that matches the provided Predicate.
func (Iterator[E]) ForEach ¶
func (iter Iterator[E]) ForEach(fn func(E))
ForEach consumes the Iterator, calling the provided function on each element of the Iterator.
func (Iterator[E]) Fuse ¶
Fuse creates an Iterator.Next that permanently ends after the first (_, false). After an Iterator.Next false,future calls may or may not yield a value and true. Fuse ensures that after a false is given, it will return false thereafter.
func (Iterator[E]) Inspect ¶
Inspect does something with each element of the Iterator before passing it on. Inspect is typically used as a debugging tool to check out the internals of a chain of iterator steps at various points in the pipeline.
Example ¶
i := FromItems(0, 1, 2, 3, 4). Inspect(func(n int) { fmt.Printf("filtering: %d\n", n) }). Filter(func(n int) bool { return n%2 == 0 }). Inspect(func(n int) { fmt.Printf("even: %d\n", n) }) fmt.Println(Sum(i))
Output: filtering: 0 even: 0 filtering: 1 filtering: 2 even: 2 filtering: 3 filtering: 4 even: 4 6
func (Iterator[E]) Intersperse ¶
Intersperse creates a new Iterator which places the provided separator between subsequent elements.
Example ¶
sl := FromItems(0, 1, 2).Intersperse(3).ToSlice() fmt.Println(sl)
Output: [0 3 1 3 2]
func (Iterator[E]) IntersperseWith ¶
IntersperseWith behaves the same as Iterator.Intersperse, but uses the provided function to generate the separator.
func (Iterator[E]) Last ¶
Last calls Iterator.Next repeatedly until the first time ok is false, returning the last element seen. The ok value is false if the Iterator is already finished.
func (Iterator[E]) MaxBy ¶
MaxBy consumes the provided Iterator, returning the maximum value determined by the specified LessFunc.
func (Iterator[E]) MinBy ¶
MinBy consumes the Iterator, returning the minimum value determined by the specified LessFunc.
func (Iterator[E]) Next ¶
Next advances the iterator and returns the next element. The ok value is set to false when the iteration is finished. Individual iterator implementations may choose to resume iteration, and so calling Next again may or may not eventually start returning values again at some point.
func (Iterator[E]) Nth ¶
Nth returns the zero-indexed element of the iterator. This method will return ok as false if n is greater than or equal to the length of the iterator.
func (Iterator[E]) Partition ¶
Partition applies the provided Predicate to the iterator, returning two slices of elements matching or not matching, respectively.
func (Iterator[E]) Peekable ¶
func (iter Iterator[E]) Peekable() PeekIterator[E]
Peekable converts the current Iterator into a PeekIterator.
func (Iterator[E]) Position ¶
Position returns the zero-based index of the element in the Iterator that matches the provided Predicate.
func (Iterator[E]) Reduce ¶
func (iter Iterator[E]) Reduce(fn ReduceFunc[E]) (result E, ok bool)
Reduce is a specialization of Fold that uses the first element of the Iterator as the initial accumulator value. The ok value is false if the iterator is empty.
func (Iterator[E]) Skip ¶
Skip returns a new Iterator that advances the current iterator by n before returning the Next element.
func (Iterator[E]) SkipWhile ¶
SkipWhile returns a new Iterator that will skip values matching the provided Predicate until the first element that does not match. After the first non-matching element, the predicate is no longer applied.
func (Iterator[E]) StepBy ¶
StepBy returns a new iterator that returns every nth (one-indexed) element. The first element in the iterator is always returned, followed by every nth element thereafter. If n is equal to one, this method is a noop.
func (Iterator[E]) Take ¶
Take returns a new Iterator that limits the number of elements returned to the specified number.
func (Iterator[E]) TakeWhile ¶
TakeWhile returns a new Iterator that emits values that match the provided Predicate, stopping after the first non-match.
func (Iterator[E]) ToChan ¶
func (iter Iterator[E]) ToChan() (ch <-chan E, cancel context.CancelFunc)
ToChan converts the current Iterator into a channel. Note that the returned context.CancelFunc should always be called once use of the channel is complete to ensure background goroutines are cleaned up.
Example ¶
ch, cancel := FromItems(1, 2, 3).ToChan() defer cancel() fmt.Print(<-ch) fmt.Print(<-ch) fmt.Println(<-ch)
Output: 123
func (Iterator[E]) ToChanWithContext ¶
func (iter Iterator[E]) ToChanWithContext(ctx context.Context) (ch <-chan E, cancel context.CancelFunc)
ToChanWithContext converts the current Iterator into a channel. If ctx is canceled, the returned channel will be closed, and the iterator may not be fully exhausted. Note that the returned context.CancelFunc should always be called once use of the channel is complete to ensure background goroutines are cleaned up.
func (Iterator[E]) ToSlice ¶
func (iter Iterator[E]) ToSlice() []E
ToSlice collects the elements of the Iterator into a slice.
func (Iterator[E]) TryFind ¶
func (iter Iterator[E]) TryFind(pred TryPredicate[E]) (match E, ok bool, err error)
TryFind behaves the same as Find, but will stop execution if the provided TryPredicate returns an error.
func (Iterator[E]) TryForEach ¶
TryForEach performs the same behavior as ForEach, but if the provided function returns an error, execution stops early and the error is returned.
type KeyFunc ¶
type KeyFunc[T any, K constraints.Ordered] MapFunc[T, K]
KeyFunc converts a value of any type into a constraints.Ordered value that can be used to compare values.
type LessFunc ¶
LessFunc compares two values, returning true if the first value is less than the second.
type MapFunc ¶
type MapFunc[A, B any] func(from A) (to B)
MapFunc converts a value of type A into a value of type B.
type Number ¶
type Number interface { constraints.Integer | constraints.Float | constraints.Complex }
Number is a constraint describing any Go numerical type that supports arithmetic operations.
type PeekCore ¶
type PeekCore[E any] interface { Core[E] // Peek looks ahead to the next element, without advancing the Core. Peek() (E, bool) }
A PeekCore extends a Core to also provide Peek functionality. Custom implementations of a Core may expose specialized (e.g., more efficient) Peek methods via this interface; otherwise, Iterator.Peekable will upgrade any iterator to a PeekIterator.
type PeekIterator ¶
A PeekIterator is an Iterator that also supports the Peek operation. A PeekIterator may be created directly via FromPeekCore or by upgrading an existing Iterator via Iterator.Peekable.
func FromPeekCore ¶
func FromPeekCore[E any](core PeekCore[E]) PeekIterator[E]
FromPeekCore converts a PeekCore into a PeekIterator.
func (PeekIterator[E]) Peek ¶
func (pi PeekIterator[E]) Peek() (next E, ok bool)
Peek returns the next value without advancing the Iterator.
func (PeekIterator[E]) Peekable ¶
func (pi PeekIterator[E]) Peekable() PeekIterator[E]
Peekable on a PeekIterator is as noop.
type Predicate ¶
A Predicate function receives a value and returns true if the value matches the predicate and should be emitted.
type ReduceFunc ¶
ReduceFunc is a FoldFunc that uses the same type for the state and element values.
type ScanFunc ¶
A ScanFunc receives a pointer to the current state and the next value, returning a result value and ok indicating if the iterator should continue.
type TryFoldFunc ¶
TryFoldFunc is a FoldFunc that may also return an error, short-circuiting accumulation.
type TryPredicate ¶
A TryPredicate is a predicate that is fallible, returning an error if execution should short-circuit.
type TryReduceFunc ¶
type TryReduceFunc[T any] TryFoldFunc[T, T]
TryReduceFunc is a TryFoldFunc that uses the same type for the state and element values.