Documentation
¶
Overview ¶
The iterator package provides implementation for the creation, consumption and transformation of various types kinds of generic iterators.
Features ¶
Iterators in this package have the following features:
Support for iteration over single elements or key/value pairs.
Constructable over slices, maps and from literal elements.
Support for mutation of elements and underlying collections.
Collectable into slices or maps.
Transformable via various mapping, filtering and reducing methods.
Types of iterators ¶
There are four main iterator types, encapsulated in four interfaces.
- iterator.Iterator - A standard generic iterator that yields single values.
- iterator.Iterator2 - An iterator that yields pairs of values, typically a value plus a key.
- iterator.MutableIterator - An extension of iterator.Iterator that allows modification and removal of values from some underlying collection (such as slice).
- iterator.MutableIterator2 - An extension of iterator.Iterator2 that allows modification and removal of key value pairs from some underlying collection (such as map). Note that only the value can be modified, not the key.
The above top level interfaces are composite definitions such that instances of any of them will also implement other key interfaces.
Any iterator.Iterator[T] also implements:
Any iterator.Iterator2[K,V] also implements:
Any iterator.MutableIterator[T] also implements:
Any iterator.MutableIterator2[K,V] also implements:
Construction ¶
Out of the box methods exist to produce iterators:
- Over slices via github.com/robdavid/genutil-go/slices.Iter, github.com/robdavid/genutil-go/slices.IterRef or github.com/robdavid/genutil-go/slices.IterMut methods.
- Over maps via github.com/robdavid/genutil-go/maps.Iter, github.com/robdavid/genutil-go/maps.IterMut.
- Over number ranges via iterator.Range, iterator.IncRange, iterator.RangyBy or iterator.IncRangeBy functions.
- Over an explicit list of elements via the iterator.Of function.
User iterators ¶
New iterators can be created a number of ways.
- An iter.Seq function can be transformed to an iterator.Iterator via the iterator.New or iterator.NewWithSize functions. This is the simplest and most recommended way to build an iterator.
- An iter.Seq2 function can be transformed to an iterator.Iterator2 via the iterator.New2 or iterator.New2WithSize functions. This is the simplest and most recommended way to build an iterator of key/value pairs.
- A user may create an implementation of iterator.SimpleIterator and convert it to an iterator.Iterator with iterator.NewFromSimple or iterator.NewFromSimpleWithSize.
- A user may create an implementation of iterator.SimpleMutableIterator and convert it to an iterator.MutableIterator with iterator.NewFromSimpleMutable or iterator.NewFromSimpleMutableWithSize.
- A user may create an implementation of iterator.CoreIterator and convert it to an iterator.Iterator with iterator.NewDefaultIterator.
- A user may create an implementation of iterator.CoreMutableIterator and convert it to an iterator.MutableIterator with iterator.NewDefaultMutableIterator.
- A user may create an implementation of iterator.CoreIterator2 and convert it to an iterator.Iterator2 with iterator.NewDefaultIterator2.
- A user may create an implementation of iterator.CoreMutableIterator2 and convert it to an iterator.MutableIterator2 with iterator.NewDefaultMutableIterator2.
Consumption ¶
The most straightforward and recommended way to consume elements from an iterator is to use the iterator.CoreIterator.Seq or iterator.CoreIterator2.Seq2 methods to convert the iterator to an iter.Seq or iter.Seq2 object, and use a for loop, eg:
for n := range iterator.Range(0, 5).Seq() {
fmt.Printf("%d\n", n)
}
// Output:
// 0
// 1
// 2
// 3
// 4
This is usually the most efficient approach, especially if the iterator is build on top of an iter.Seq or iter.Seq2 already. However, you can also loop over the iterator using the iterator.SimpleIterator.Next and iterator.SimpleIterator.Value methods, eg:
for itr := iterator.Range(0, 5); itr.Next(); {
fmt.Printf("%d\n", itr.Value())
}
// Output:
// 0
// 1
// 2
// 3
// 4
It is also possible to collect all the elements in an iterator into a slice or a map.
An iterator.CoreIterator may be collected into a slice using one of the following methods:
- iterator.DefaultIterator.Collect
- iterator.DefaultIterator.CollectInto
- iterator.DefaultIterator.CollectIntoCap
An iterator.CoreIterator2 may be collected into a slice of iterator.KeyValue elements via one of the following methods:
- iterator.DefaultIterator.Collect2
- iterator.DefaultIterator.Collect2Into
- iterator.DefaultIterator.Collect2IntoCap
An iterator.CoreIterator2 may be collected into a map via one of the following functions:
Transformations ¶
Iterator types support a number of transformation methods and functions covering such things as filtering, mapping and folding over elements. These are defined in interface definitions iterator.IteratorExtensions and iterator.Iterator2Extensions. Default implementations are provided by iterator.DefaultIterator and iterator.DefaultIterator2. These are listed below.
- iterator.DefaultIterator.All
- iterator.DefaultIterator.Any
- iterator.DefaultIterator.Chan
- iterator.DefaultIterator2.Chan2
- iterator.DefaultIterator.Collect
- iterator.DefaultIterator2.Collect2
- iterator.DefaultIterator2.Collect2Into
- iterator.DefaultIterator2.Collect2IntoCap
- iterator.DefaultIterator.CollectInto
- iterator.DefaultIterator.CollectIntoCap
- iterator.DefaultIterator.Enumerate
- iterator.DefaultIterator.Filter
- iterator.DefaultIterator2.Filter2
- iterator.DefaultIterator.FilterMorph
- iterator.DefaultIterator2.FilterMorph2
- iterator.DefaultIterator.Fold
- iterator.DefaultIterator.Fold1
- iterator.DefaultIterator.Intercalate
- iterator.DefaultIterator.Intercalate1
- iterator.DefaultIterator.Morph
- iterator.DefaultIterator2.Morph2
- iterator.DefaultIterator.Take
- iterator.DefaultIterator2.Take2
There are also corresponding functions in the iterator package, which include some additional or modified functions that can't be expressed as methods due to limitations of generics. All methods defined in iterator.DefaultIterator or iterator.DefaultIterator2 delegate to one of these functions.
- iterator.All
- iterator.Any
- iterator.Chan
- iterator.Chan2
- iterator.Take
- iterator.Collect
- iterator.Collect2
- iterator.Collect2Into
- iterator.Collect2IntoCap
- iterator.CollectInto
- iterator.CollectIntoCap
- iterator.CollectIntoMap
- iterator.CollectMap
- iterator.Enumerate
- iterator.Filter
- iterator.Filter2
- iterator.FilterMap
- iterator.FilterMap2
- iterator.Fold
- iterator.Fold1
- iterator.Intercalate
- iterator.Intercalate1
- iterator.Map
- iterator.Map2
- iterator.Seq
- iterator.Seq2
- iterator.Take
- iterator.Take2
*
Index ¶
- Variables
- func All[T any](itr CoreIterator[T], predicate func(v T) bool) bool
- func Any[T any](itr CoreIterator[T], predicate func(v T) bool) bool
- func Chan[T any](itr CoreIterator[T]) (out chan T)
- func Chan2[K any, V any](itr CoreIterator2[K, V]) (out chan KeyValue[K, V])
- func Collect[T any](iter CoreIterator[T]) []T
- func CollectInto[T any](iter CoreIterator[T], slice *[]T) []T
- func CollectIntoCap[T any](iter CoreIterator[T], slice *[]T) []T
- func CollectIntoMap[K comparable, V any](iter CoreIterator2[K, V], m map[K]V) map[K]V
- func CollectMap[K comparable, V any](itr CoreIterator2[K, V]) map[K]V
- func CollectResults[T any](iter CoreIterator[result.Result[T]]) ([]T, error)
- func EmptySeq[T any]() iter.Seq[T]
- func EmptySeq2[K any, V any]() iter.Seq2[K, V]
- func Fold[U any, T any](itr CoreIterator[T], init U, f func(a U, e T) U) U
- func Fold1[T any](itr CoreIterator[T], f func(a, e T) T) T
- func Intercalate[T any](itr CoreIterator[T], empty T, inter T, f func(a, e T) T) T
- func Intercalate1[T any](itr CoreIterator[T], inter T, f func(a, e T) T) T
- func PartitionResults[T any](iter CoreIterator[result.Result[T]]) ([]T, []error)
- func Seq[T any](i SimpleIterator[T]) iter.Seq[T]
- func Seq2[K any, V any](i SimpleIterator[KeyValue[K, V]]) iter.Seq2[K, V]
- type AbortGenerator
- type Consumer
- type CoreIterator
- type CoreIterator2
- type CoreMutableIterator
- type CoreMutableIterator2
- type DefaultIterator
- func (di DefaultIterator[T]) All(predicate func(T) bool) bool
- func (di DefaultIterator[T]) Any(predicate func(T) bool) bool
- func (di DefaultIterator[T]) Chan() <-chan T
- func (di DefaultIterator[T]) Collect() []T
- func (di DefaultIterator[T]) CollectInto(slice *[]T) []T
- func (di DefaultIterator[T]) CollectIntoCap(slice *[]T) []T
- func (di DefaultIterator[T]) Enumerate() Iterator2[int, T]
- func (di DefaultIterator[T]) Filter(predicate func(T) bool) Iterator[T]
- func (di DefaultIterator[T]) FilterMorph(mapping func(T) (T, bool)) Iterator[T]
- func (di DefaultIterator[T]) Fold(init T, f func(a, e T) T) T
- func (di DefaultIterator[T]) Fold1(f func(a, e T) T) T
- func (di DefaultIterator[T]) Intercalate(empty T, inter T, f func(a, e T) T) T
- func (di DefaultIterator[T]) Intercalate1(inter T, f func(a, e T) T) T
- func (di DefaultIterator[T]) Morph(mapping func(T) T) Iterator[T]
- func (di DefaultIterator[T]) Take(n int) Iterator[T]
- type DefaultIterator2
- func (di2 DefaultIterator2[K, V]) Chan2() <-chan KeyValue[K, V]
- func (di2 DefaultIterator2[K, V]) Collect2() []KeyValue[K, V]
- func (di2 DefaultIterator2[K, V]) Collect2Into(s *[]KeyValue[K, V]) []KeyValue[K, V]
- func (di2 DefaultIterator2[K, V]) Collect2IntoCap(s *[]KeyValue[K, V]) []KeyValue[K, V]
- func (di2 DefaultIterator2[K, V]) Filter2(f func(k K, v V) bool) Iterator2[K, V]
- func (di2 DefaultIterator2[K, V]) FilterMorph2(f func(K, V) (K, V, bool)) Iterator2[K, V]
- func (di2 DefaultIterator2[K, V]) Morph2(f func(k K, v V) (K, V)) Iterator2[K, V]
- func (di2 DefaultIterator2[K, V]) Take2(n int) Iterator2[K, V]
- type DefaultMutableIterator
- type DefaultMutableIterator2
- type Generator
- type GeneratorPanic
- type Iterator
- func AsKV[K any, V any](iter2 CoreIterator2[K, V]) Iterator[KeyValue[K, V]]
- func Empty[T any]() Iterator[T]
- func Filter[T any](iter CoreIterator[T], predicate func(T) bool) Iterator[T]
- func FilterMap[T, U any](iter CoreIterator[T], mapping func(T) (U, bool)) Iterator[U]
- func FilterMapOpt[T any, U any](iter CoreIterator[T], mapping func(T) option.Option[U]) Iterator[U]
- func FilterValues[T any](iter CoreIterator[result.Result[T]]) Iterator[T]
- func Generate[T any](generator Generator[T]) Iterator[T]
- func GenerateResults[T any](generator ResultGenerator[T]) Iterator[result.Result[T]]
- func IncRange[T ordered.Real](from, upto T) Iterator[T]
- func IncRangeBy[T ordered.Real, S ordered.Real](from, upto T, by S) Iterator[T]
- func MakeIterator[T any](base SimpleIterator[T]) Iterator[T]deprecated
- func Map[T any, U any](iter CoreIterator[T], mapping func(T) U) Iterator[U]
- func New[T any](seq iter.Seq[T]) Iterator[T]
- func NewFromSimple[T any](simple SimpleIterator[T]) Iterator[T]
- func NewFromSimpleWithSize[T any](simple SimpleIterator[T], size func() IteratorSize) Iterator[T]
- func NewWithSize[T any](seq iter.Seq[T], size func() IteratorSize) Iterator[T]
- func Of[T any](elements ...T) Iterator[T]
- func Range[T ordered.Real](from, upto T) Iterator[T]
- func RangeBy[T ordered.Real, S ordered.Real](from, upto T, by S) Iterator[T]
- func Slice[T any](slice []T) Iterator[T]deprecated
- func Take[T any](n int, iter CoreIterator[T]) Iterator[T]
- type Iterator2
- func Empty2[K any, V any]() Iterator2[K, V]
- func Enumerate[T any](itr CoreIterator[T]) Iterator2[int, T]
- func Filter2[K, V any](iter CoreIterator2[K, V], predicate func(K, V) bool) Iterator2[K, V]
- func FilterMap2[K, V, X, Y any](iter CoreIterator2[K, V], mapping func(K, V) (X, Y, bool)) Iterator2[X, Y]
- func Map2[K, V, X, Y any](iter CoreIterator2[K, V], mapping func(K, V) (X, Y)) Iterator2[X, Y]
- func New2[K any, V any](seq2 iter.Seq2[K, V]) Iterator2[K, V]
- func New2WithSize[K any, V any](seq2 iter.Seq2[K, V], size func() IteratorSize) Iterator2[K, V]
- func Take2[K any, V any](n int, iter CoreIterator2[K, V]) Iterator2[K, V]
- type Iterator2Extensions
- type IteratorExtensions
- type IteratorSize
- func (isz IteratorSize) Allocate() int
- func (size IteratorSize) IsInfinite() bool
- func (size IteratorSize) IsKnown() bool
- func (size IteratorSize) IsKnownToBe(n int) bool
- func (size IteratorSize) IsMaxKnown() bool
- func (size IteratorSize) IsMaxKnownToBe(n int) bool
- func (size IteratorSize) IsUnknown() bool
- func (isz IteratorSize) Subset() IteratorSize
- type IteratorSizeType
- type KeyValue
- func Collect2[K any, V any](itr CoreIterator2[K, V]) []KeyValue[K, V]
- func Collect2Into[K any, V any](iter CoreIterator2[K, V], slice *[]KeyValue[K, V]) []KeyValue[K, V]
- func Collect2IntoCap[K any, V any](iter CoreIterator2[K, V], slice *[]KeyValue[K, V]) []KeyValue[K, V]
- func KVOf[K any, V any](key K, value V) KeyValue[K, V]
- type MutableIterator
- type MutableIterator2
- type ResultConsumer
- type ResultGenerator
- type SeqCoreIterator
- func (si *SeqCoreIterator[T]) Abort()
- func (si *SeqCoreIterator[T]) Next() (ok bool)
- func (si *SeqCoreIterator[T]) Reset()
- func (si *SeqCoreIterator[T]) Seq() iter.Seq[T]
- func (si *SeqCoreIterator[T]) SeqOK() bool
- func (si *SeqCoreIterator[T]) Size() IteratorSize
- func (si *SeqCoreIterator[T]) Value() T
- type SeqCoreIterator2
- type SeqCoreMutableIterator2
- type SimpleCoreIterator
- type SimpleCoreMutableIterator
- type SimpleIterator
- type SimpleMutableIterator
Examples ¶
- CollectMap
- DefaultIterator2.FilterMorph2
- DefaultIterator.All
- DefaultIterator.Any
- DefaultIterator.Chan
- DefaultIterator.Collect
- DefaultIterator.Filter
- DefaultIterator.FilterMorph
- DefaultIterator.Intercalate
- DefaultIterator.Morph
- DefaultIterator.Take
- Fold
- Fold1
- IncRange
- IncRange (Single)
- IncRangeBy
- Intercalate
- Intercalate1
- New
- NewDefaultIterator
- NewFromSimple
- NewFromSimpleWithSize
- Of
- Range
- Range (Descending)
- Range (Empty)
- RangeBy
- Seq
- Seq2
- SeqCoreIterator.Next
- SimpleCoreIterator.Seq
Constants ¶
This section is empty.
Variables ¶
var ErrDeleteNotImplemented = errors.New("delete not implemented")
var ErrEmptyIterator = errors.New("iterator is empty")
var ErrInvalidIteratorRange = errors.New("invalid iterator range")
var ErrInvalidIteratorSizeType = errors.New("invalid iterator size type")
var ErrSizeInfinite = errors.New("cannot consume an infinite iterator")
Functions ¶
func All ¶
func All[T any](itr CoreIterator[T], predicate func(v T) bool) bool
All returns true if predicate returns true for every value returned by the iterator. This function short circuits and does not execute in constant time; the iterator is aborted after the first value for which the predicate returns false.
func Any ¶
func Any[T any](itr CoreIterator[T], predicate func(v T) bool) bool
Any returns true if predicate returns true for any value returned by the iterator. This function short circuits and does not execute in constant time; the iterator is aborted after the first value for which the predicate returns true.
func Chan ¶ added in v0.20.0
func Chan[T any](itr CoreIterator[T]) (out chan T)
Chan takes a CoreIterator and produces a channel yielding values from the iterator.
func Chan2 ¶ added in v0.20.0
func Chan2[K any, V any](itr CoreIterator2[K, V]) (out chan KeyValue[K, V])
Chan2 takes a CoreIterator2 and produces a channel yielding key and value pairs from the iterator.
func Collect ¶
func Collect[T any](iter CoreIterator[T]) []T
Collect all elements from an iterator into a slice. If the iterator is known to be of infinite size, this function will panic.
func CollectInto ¶ added in v0.16.0
func CollectInto[T any](iter CoreIterator[T], slice *[]T) []T
CollectInto collects all elements from an iterator into a slice a pointer to which is passed. Elements are appended to any existing data in the slice. The slice referenced may be reallocated as the append function is used to add elements to the slice. The slice may be a nil slice. For convenience, the final slice is returned. If the iterator is known to have an infinite size, this function will panic.
func CollectIntoCap ¶ added in v0.20.0
func CollectIntoCap[T any](iter CoreIterator[T], slice *[]T) []T
CollectIntoCap appends elements from an iterator into a slice a pointer to which is passed, up to a maximum of the capacity for the slice. Elements are not added beyond the capacity. Elements are appended to any existing data in the slice. The slice may be a nil slice, in which case no elements will be added. For convenience, tbe final slice is returned.
func CollectIntoMap ¶ added in v0.20.0
func CollectIntoMap[K comparable, V any](iter CoreIterator2[K, V], m map[K]V) map[K]V
CollectIntoMap collects all element pairs from an Iterator2 into the map passed, populating it with key and value pairs. All keys should be unique; any duplicate keys will result in only the latest key/value pair with that key being preserved. The map may be nil, in which case a new map will be created. The final map is returned. If the iterator is known to have an infinite size, this function will panic.
func CollectMap ¶ added in v0.20.0
func CollectMap[K comparable, V any](itr CoreIterator2[K, V]) map[K]V
CollectMap collects all elements from an Iterator2 into a map of key and value pairs. All keys should be unique; any duplicate keys will result in only the latest key/value pair with that key being preserved. If the iterator is known to be of infinite size, this function will panic.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
i := iterator.Of("zero", "one", "two", "three").Enumerate()
m := iterator.CollectMap(i)
fmt.Printf("%#v\n", m)
}
Output: map[int]string{0:"zero", 1:"one", 2:"two", 3:"three"}
func CollectResults ¶
func CollectResults[T any](iter CoreIterator[result.Result[T]]) ([]T, error)
CollectResults collects all elements from an iterator of results into a result of slice of the iterator's underlying type If the iterator returns an error result at any point, this call will terminate and return that error, along with the elements collected thus far.
func Fold ¶ added in v0.20.0
func Fold[U any, T any](itr CoreIterator[T], init U, f func(a U, e T) U) U
Fold combines the elements of an iterator into a single value using an accumulation function. It takes an iterator, an initial value init and an accumulation function f. If the iterator is empty, init is returned. Otherwise the initial value is fed into the accumulation function f along with the first element from the iterator. The result is then fed back into f along with the second element, and so on. The final result is the final value returned by the function. If the iterator is known to be of infinite size, this function will panic with ErrSizeInfinite.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
add := func(a, b int) int { return a + b }
s := iterator.Fold(iterator.IncRange(1, 5), 0, add)
fmt.Println(s)
}
Output: 15
func Fold1 ¶ added in v0.20.0
func Fold1[T any](itr CoreIterator[T], f func(a, e T) T) T
Fold1 combines the elements of an iterator into a single value using an accumulation function. It takes an iterator, an initial value init and an accumulation function f. The iterator must have at least one element, or this function will panic with ErrEmptyIterator. If there is only one element, this element be returned. Otherwise, the first two elements are fed into the accumulation function f. The result of this is combined with the next element to get the next result and so on until the iterator is consumed. The final result is returned. If the iterator is known to be of infinite size, this function will panic with ErrSizeInfinite.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
mul := func(a, b int) int { return a * b }
s := iterator.Fold1(iterator.Of(2, 3, 4), mul)
fmt.Println(s)
}
Output: 24
func Intercalate ¶ added in v0.20.0
func Intercalate[T any](itr CoreIterator[T], empty T, inter T, f func(a, e T) T) T
Intercalate is a variation on Fold which combines the elements of an iterator into a single value using an accumulation function and an interspersed value. If the iterator has no elements, the empty parameter is returned. Otherwise, the accumulated result is initially set to the first element, and is combined with subsequent elements as follows:
acc = f(f(acc,inter),e)
where acc is he accumulated value, e is the next element and inter is the inter parameter, and the final value of acc will be the value returned. If the iterator is known to be of infinite size, this function will panic with ErrSizeInfinite.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/functions"
"github.com/robdavid/genutil-go/iterator"
"github.com/robdavid/genutil-go/slices"
)
func main() {
inputs := []string{"one", "two", "three"}
for l := range len(inputs) + 1 {
s := iterator.Intercalate(slices.Iter(inputs[:l]), "", " ", functions.Sum)
fmt.Printf("%#v\n", s)
}
}
Output: "" "one" "one two" "one two three"
func Intercalate1 ¶ added in v0.20.0
func Intercalate1[T any](itr CoreIterator[T], inter T, f func(a, e T) T) T
Intercalate1 is a variation on Fold1 which combines the elements of an iterator into a single value using an accumulation function and an interspersed value. The iterator must have at least one element, otherwise it will panic with ErrEmptyIterator. The accumulated result is initially set to the first element, and is combined with subsequent elements as follows:
acc = f(f(acc,inter),e)
where acc is he accumulated value, e is the next element and inter is the inter parameter. The final value of acc will be the value returned. If the iterator is known to be of infinite size, this function will panic with ErrSizeInfinite.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/functions"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
s1 := iterator.Intercalate1(iterator.Of("Hello"), " ", functions.Sum)
fmt.Println(s1)
s := iterator.Intercalate1(iterator.Of("Hello", "world"), " ", functions.Sum)
fmt.Println(s)
}
Output: Hello Hello world
func PartitionResults ¶
func PartitionResults[T any](iter CoreIterator[result.Result[T]]) ([]T, []error)
PartitionResults collects the elements from an iterator of result types into two slices, one of successful (nil error) values, and the other of error values.
func Seq ¶ added in v0.20.0
func Seq[T any](i SimpleIterator[T]) iter.Seq[T]
Seq transforms any generic SimpleIterator into a native iter.Seq iterator.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
for n := range iterator.Seq(iterator.Range(0, 5)) {
fmt.Printf("%d\n", n)
}
}
Output: 0 1 2 3 4
func Seq2 ¶ added in v0.20.0
Seq2 transforms a SimpleIterator of KeyValue pairs into a native iter.Seq2 iterator.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
// Create an iterator of [KeyValue] pairs from enumerated range
iterKV := iterator.AsKV(iterator.Range(5, 10).Enumerate())
for k, v := range iterator.Seq2(iterKV) {
fmt.Printf("%d: %d\n", k, v)
}
}
Output: 0: 5 1: 6 2: 7 3: 8 4: 9
Types ¶
type AbortGenerator ¶
type AbortGenerator struct{}
AbortGenerator is a panic type that will be raised if a Generator function is to be aborted.
type Consumer ¶ added in v0.16.0
type Consumer[T any] struct { // contains filtered or unexported fields }
Consumer is a type, an instance of which is passed to a Generator generator function. Values from the function can be yielded to the generator via the Yield method (or an error via the YieldError method).
type CoreIterator ¶ added in v0.20.0
type CoreIterator[T any] interface { SimpleIterator[T] // Seq returns the iterator as a Go [iter.Seq] iterator. The iterator may be // backed by an iter.Seq[T] object, in which case that iterator object will // typically be returned directly. Otherwise, an iter.Seq[T] will be // synthesised from the underlying iterator, typically a [SimpleIterator]. Seq() iter.Seq[T] // Size is an estimate, where possible, of the number of elements remaining. Size() IteratorSize // SeqOK returns true if the Seq() method should be used to perform // iterations. Generally, using Seq() is the preferred method for efficiency // reasons. However there are situations where this is not the case and in // those cases this method will return false. For example, if the underlying // iterator is based on a simple iterator, it is slightly more efficient to // stick to the simple iterator methods. Also, if simple iterator methods // have already been called against a Seq based iterator, calling Seq() will // cause inconsistent results, as it will restart the iterator from the // beginning, and so in these cases, SeqOK() will return false. SeqOK() bool }
CoreIterator is an extension of SimpleIterator that in aggregate provides the minimum set of methods that are intrinsic to an iterator implementation, i.e. those methods that are concerned with interacting the underlying data.
type CoreIterator2 ¶ added in v0.20.0
type CoreIterator2[K any, V any] interface { CoreIterator[V] // Seq returns the iterator as a Go [iter.Seq2] iterator. The iterator may // be backed by an iter.Seq2[T] object, in which case that iterator object // will typically be returned directly. Otherwise, an iter.Seq2[T] will be // synthesized from the underlying iterator. Seq2() iter.Seq2[K, V] // Key returns the current iterator key. Key() K }
CoreIterator2 is an extension of CoreIterator that adds support for a second variable of type K (the "key") in addition to the existing value, of type V.
type CoreMutableIterator ¶ added in v0.20.0
type CoreMutableIterator[T any] interface { CoreIterator[T] // Set modifies the current value, the last value arrived at by a call to // Next(), in place. Set(T) // Delete deletes the current value, which must be the last value returned // by Next(). This function may not be implemented for all iterator types, // in which case it will panic. Delete() }
CoreMutableIterator is an extension of CoreIterator which adds methods to facilitate iterator mutation.
func NewSliceCoreIterator ¶ added in v0.20.0
func NewSliceCoreIterator[T any](slice *[]T) CoreMutableIterator[T]
func NewSliceCoreIteratorRef ¶ added in v0.20.0
func NewSliceCoreIteratorRef[T any](slice *[]T) CoreMutableIterator[*T]
type CoreMutableIterator2 ¶ added in v0.20.0
type CoreMutableIterator2[K any, V any] interface { CoreIterator2[K, V] // Set will modify the current iterator value. Set(V) // Delete will remove the current iterator item. Calling Next() is still // required to advance to the next item. Delete() }
CoreMutableIterator2 is an extension of CoreIterator2 that adds support for mutability. The iterator value may be changed, and the current item may be deleted. There is no support for modifying the key.
type DefaultIterator ¶ added in v0.20.0
type DefaultIterator[T any] struct { CoreIterator[T] }
DefaultIterator wraps a CoreIterator and provides default implementations of the iterator methods defined in IteratorExtensions to provide a complete Iterator implementation. All the extension methods are written purely in terms of the methods of CoreIterator, any typically delegate to the function in the iterator package of the same name.
func NewDefaultIterator ¶ added in v0.20.0
func NewDefaultIterator[T any](citr CoreIterator[T]) DefaultIterator[T]
NewDefaultIterator builds an Iterator from a CoreIterator by adding the methods defined in IteratorExtensions.
Example ¶
package main
import (
"fmt"
"iter"
"github.com/robdavid/genutil-go/iterator"
)
// coreCounter is a CoreIterator implementation that produces an
// infinite string of integers, starting from 0.
type coreCounter struct {
value int
count int
aborted bool
}
// Next sets value to the next count, increments the count, and
// returns true, unless aborted. When aborted, it is a no-op.
func (c *coreCounter) Next() bool {
if c.aborted {
return false
} else {
c.value = c.count
c.count++
return true
}
}
// Value returns the current value.
func (c *coreCounter) Value() int {
return c.value
}
// Abort stops the iterator by setting the aborted flag.
func (c *coreCounter) Abort() {
c.aborted = true
}
// Reset sets the counter back to 0.
func (c *coreCounter) Reset() {
c.count = 0
}
// Seq implements the [CoreIterator] method Seq() by delegating to [iterator.Seq].
func (c *coreCounter) Seq() iter.Seq[int] {
return iterator.Seq(c)
}
// SeqOK returns false since this iterator is not backed by an [iter.Seq], and it's
// slightly more efficient to use Next/Value to consume it.
func (c coreCounter) SeqOK() bool { return false }
// Size returns a value indicating this iterator does not terminate and returns
// an infinite number of items.
func (c coreCounter) Size() iterator.IteratorSize {
return iterator.SIZE_INFINITE
}
func main() {
i := iterator.NewDefaultIterator(&coreCounter{})
func() {
defer func() { fmt.Println(recover()) }()
i.Collect() // Attempting to collect the infinite iterator will panic.
}()
c := i.Take(10).Collect() // Collecting only the first 10 elements succeeds.
fmt.Println(c)
}
Output: cannot consume an infinite iterator [0 1 2 3 4 5 6 7 8 9]
func (DefaultIterator[T]) All ¶ added in v0.20.0
func (di DefaultIterator[T]) All(predicate func(T) bool) bool
All returns true if p returns true for all the elements in the iterator. This method short circuits and does not execute in constant time; the iterator is aborted after the first value for which the predicate returns false.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
// prime returns true if n is prime, otherwise false. It tries to find a factor
// by dividing by every number less than itself, and greater than 1.
func prime(n int) bool {
for f := 2; f < n; f++ {
if n%f == 0 {
return false
}
}
return true
}
func main() {
fmt.Println(iterator.Range(3, 10).All(prime))
fmt.Println(iterator.Of(1, 2, 3, 5, 7, 11).All(prime))
}
Output: false true
func (DefaultIterator[T]) Any ¶ added in v0.20.0
func (di DefaultIterator[T]) Any(predicate func(T) bool) bool
Any returns true if p returns true for at least one element in the iterator. This method short circuits and does not execute in constant time; the iterator is aborted after the first value for which the predicate returns true.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
// prime returns true if n is prime, otherwise false. It tries to find a factor
// by dividing by every number less than itself, and greater than 1.
func prime(n int) bool {
for f := 2; f < n; f++ {
if n%f == 0 {
return false
}
}
return true
}
func main() {
fmt.Println(iterator.Range(3, 10).Any(prime))
fmt.Println(iterator.RangeBy(4, 10, 2).Any(prime))
}
Output: true false
func (DefaultIterator[T]) Chan ¶ added in v0.20.0
func (di DefaultIterator[T]) Chan() <-chan T
Chan returns the iterator as a channel. The iterator is consumed in a goroutine which yields results to the channel.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
for n := range iterator.Range(0, 5).Chan() {
fmt.Println(n)
}
}
Output: 0 1 2 3 4
func (DefaultIterator[T]) Collect ¶ added in v0.20.0
func (di DefaultIterator[T]) Collect() []T
Collect collects all elements from the iterator into a slice.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
c := iterator.Range(0, 5).Collect()
fmt.Printf("%#v\n", c)
}
Output: []int{0, 1, 2, 3, 4}
func (DefaultIterator[T]) CollectInto ¶ added in v0.20.0
func (di DefaultIterator[T]) CollectInto(slice *[]T) []T
CollectInto adds all elements from the iterator into an existing slice.
func (DefaultIterator[T]) CollectIntoCap ¶ added in v0.20.0
func (di DefaultIterator[T]) CollectIntoCap(slice *[]T) []T
CollectIntoCap add elements from the iterator into an existing slice until either the capacity of the slice is filled, or the iterator is exhausted, which ever is first.
func (DefaultIterator[T]) Enumerate ¶ added in v0.20.0
func (di DefaultIterator[T]) Enumerate() Iterator2[int, T]
Enumerate returns an iterator that enumerates the elements of this iterator, returning an Iterator2 of the index and the value.
func (DefaultIterator[T]) Filter ¶ added in v0.20.0
func (di DefaultIterator[T]) Filter(predicate func(T) bool) Iterator[T]
Filter is a filtering method that creates a new iterator which contains a subset of elements contained in the current one. This function takes a predicate function p and only elements for which this function returns true should be included in the filtered iterator.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
predicate := func(n int) bool { return n%2 == 0 }
i := iterator.IncRange(1, 5).Filter(predicate)
c := i.Collect()
fmt.Printf("%#v\n", c)
}
Output: []int{2, 4}
func (DefaultIterator[T]) FilterMorph ¶ added in v0.20.0
func (di DefaultIterator[T]) FilterMorph(mapping func(T) (T, bool)) Iterator[T]
FilterMorph is a filtering and mapping method that creates a new iterator from an existing one by simultaneously transforming and filtering each iterator element. The method takes a mapping function f that transforms and filters each element. It does this by taking an input element value and returning a new element value and a boolean flag. Only elements for which this flag is true are included in the new iterator. E.g.
itr := iterator.Of(0,1,2,3,4)
itrMorph := itr.FilterMorph(func(v int) (int, bool) { return v*2, v%2 == 0})
result := itrMorph.Collect() // []int{0,4,8}
Note that this function is not able to map elements to values of a different type due to limitations of Go generics. For a filter mapping function that can change the type, see the iterator.FilterMap function.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
// Function to filter on even values, doubling each selected value.
f := func(v int) (int, bool) { return v * 2, v%2 == 0 }
i := iterator.Of(0, 1, 2, 3, 4).FilterMorph(f)
c := i.Collect()
fmt.Printf("%#v\n", c)
}
Output: []int{0, 4, 8}
func (DefaultIterator[T]) Fold ¶ added in v0.20.0
func (di DefaultIterator[T]) Fold(init T, f func(a, e T) T) T
Fold combines the elements of the iterator into a single value using an accumulation function. It takes an initial value init and the accumulation function f. If the iterator is empty, init is returned. Otherwise the initial value is fed into the accumulation function f along with the first element from the iterator. The result is then fed back into f along with the second element, and so on until the iterator is consumed. The final result is the final value returned by the function. If the iterator is known to be of infinite size, this method will panic with ErrSizeInfinite.
func (DefaultIterator[T]) Fold1 ¶ added in v0.20.0
func (di DefaultIterator[T]) Fold1(f func(a, e T) T) T
Fold1 combines the elements of the iterator into a single value using an accumulation function. It takes an initial value init and an accumulation function f. The iterator must have at least one element, or this method will panic with ErrEmptyIterator. If there is only one element, this element be returned. Otherwise, the first two elements are fed into the accumulation function f. The result of this is combined with the next element to get the next result and so on until the iterator is consumed. The final result is returned. If the iterator is known to be of infinite size, this method will panic with ErrSizeInfinite.
func (DefaultIterator[T]) Intercalate ¶ added in v0.20.0
func (di DefaultIterator[T]) Intercalate(empty T, inter T, f func(a, e T) T) T
Intercalate is a variation on Fold which combines the elements of the iterator into a single value using an accumulation function and an interspersed value. If the iterator has no elements, the empty parameter is returned. Otherwise, the accumulated result is initially set to the first element, and is combined with subsequent elements as follows:
acc = f(f(acc,inter),e)
where acc is he accumulated value, e is the next element and inter is the inter parameter, and the final value of acc will be the value returned. If the iterator is known to be of infinite size, this function will panic with ErrSizeInfinite.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/functions"
"github.com/robdavid/genutil-go/slices"
)
func main() {
inputs := []string{"one", "two", "three"}
for l := range len(inputs) + 1 {
s := slices.Iter(inputs[:l]).Intercalate("", " ", functions.Sum)
fmt.Printf("%#v\n", s)
}
}
Output: "" "one" "one two" "one two three"
func (DefaultIterator[T]) Intercalate1 ¶ added in v0.20.0
func (di DefaultIterator[T]) Intercalate1(inter T, f func(a, e T) T) T
Intercalate1 is a variation on Fold1 which combines the elements of the iterator into a single value using an accumulation function and an interspersed value. The iterator must have at least one element, otherwise it will panic with ErrEmptyIterator. The accumulated result is initially set to the first element, and is combined with subsequent elements as follows:
acc = f(f(acc,inter),e)
where acc is he accumulated value, e is the next element and inter is the inter parameter. The final value of acc will be the value returned. If the iterator is known to be of infinite size, this function will panic with ErrSizeInfinite.
func (DefaultIterator[T]) Morph ¶ added in v0.20.0
func (di DefaultIterator[T]) Morph(mapping func(T) T) Iterator[T]
Morph is a mapping function that creates a new iterator which contains the elements of the current iterator with the supplied function m applied to each one. The type of the return value of m must be the same as that of the elements of the current iterator. This is because of limitations of Go generics. To apply a mapping that changes the type, see the Map function.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
f := func(n int) int { return n * 2 }
i := iterator.Range(0, 5).Morph(f)
c := i.Collect()
fmt.Printf("%#v\n", c)
}
Output: []int{0, 2, 4, 6, 8}
func (DefaultIterator[T]) Take ¶ added in v0.20.0
func (di DefaultIterator[T]) Take(n int) Iterator[T]
Take returns a variant of the current iterator that which returns at most n elements. If the current iterator has less than or exactly n elements, the returned iterator is equivalent to the input iterator.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
i := iterator.Range(0, 100).Take(5)
c := i.Collect()
fmt.Printf("%#v\n", c)
}
Output: []int{0, 1, 2, 3, 4}
type DefaultIterator2 ¶ added in v0.20.0
type DefaultIterator2[K any, V any] struct { CoreIterator2[K, V] IteratorExtensions[V] }
DefaultIterator2 is an Iterator2 implementation which embeds CoreIterator2 and IteratorExtensions interfaces, and implements the methods of [IteratorExtensions2] in terms of CoreIterator2. It can be constructed solely from a CoreIterator2 implementation by the NewDefaultIterator2 function.
func NewDefaultIterator2 ¶ added in v0.20.0
func NewDefaultIterator2[K any, V any](core CoreIterator2[K, V]) DefaultIterator2[K, V]
NewDefaultIterator2 constructs an Iterator2 by wrapping a CoreIterator2 with a DefaultIterator2 to add the additional IteratorExtensions and [IteratorExtensions2] methods to provide the complete Iterator2 implementation
func (DefaultIterator2[K, V]) Chan2 ¶ added in v0.20.0
func (di2 DefaultIterator2[K, V]) Chan2() <-chan KeyValue[K, V]
Chan2 returns the iterator as a channel of KeyValue objects. The iterator is consumed in a goroutine which yields results to the channel.
func (DefaultIterator2[K, V]) Collect2 ¶ added in v0.20.0
func (di2 DefaultIterator2[K, V]) Collect2() []KeyValue[K, V]
Collect2 collects all the element pairs from the iterator into a slice of KeyValue objects.
func (DefaultIterator2[K, V]) Collect2Into ¶ added in v0.20.0
func (di2 DefaultIterator2[K, V]) Collect2Into(s *[]KeyValue[K, V]) []KeyValue[K, V]
Collect2Into collects all the element pairs from the iterator into the slice of KeyValue objects pointed to by s. The final slice is returned.
func (DefaultIterator2[K, V]) Collect2IntoCap ¶ added in v0.20.0
func (di2 DefaultIterator2[K, V]) Collect2IntoCap(s *[]KeyValue[K, V]) []KeyValue[K, V]
Collect2IntoCap collects all the element pairs from the iterator into the slice of KeyValue objects pointed to by s, up to but not exceeding the capacity of *s. The final slice is returned.
func (DefaultIterator2[K, V]) Filter2 ¶ added in v0.20.0
func (di2 DefaultIterator2[K, V]) Filter2(f func(k K, v V) bool) Iterator2[K, V]
Filter2 is a filtering method that creates a new iterator which contains a subset of element pairs contained by the current one. This function takes a predicate function p and only element pairs for which this function returns true should be included in the filtered iterator.
func (DefaultIterator2[K, V]) FilterMorph2 ¶ added in v0.20.0
func (di2 DefaultIterator2[K, V]) FilterMorph2(f func(K, V) (K, V, bool)) Iterator2[K, V]
FilterMorph2 is a filtering and mapping method that creates a new iterator from an existing one by simultaneously transforming and filtering each iterator element pair. The method takes a mapping function f that transforms and filters each element pair. It does this by taking an input element key and value and returning a new element key and value and a boolean flag. Only elements for which this flag is true are included in the new iterator.
Note that this function is not able to map element keys or values to different types due to limitations of Go generics. For a filter mapping function that can map to different types, see the iterator.FilterMap2 function.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
"github.com/robdavid/genutil-go/maps"
)
func main() {
// Function to filter on even values, doubling each selected value.
inputMap := map[int]int{0: 2, 1: 4, 2: 6, 3: 8}
itr := maps.Iter(inputMap).FilterMorph2(func(k, v int) (int, int, bool) {
return k + 1, v * 2, (k+v)%2 == 0
})
c := iterator.CollectMap(itr)
fmt.Printf("%#v\n", c)
}
Output: map[int]int{1:4, 3:12}
func (DefaultIterator2[K, V]) Morph2 ¶ added in v0.20.0
func (di2 DefaultIterator2[K, V]) Morph2(f func(k K, v V) (K, V)) Iterator2[K, V]
Morph2 is a mapping function that creates a new iterator which contains pairs of elements of the current iterator with the supplied function m applied to each key and value. The type of the return value and key of m must be of the same type as the kay and value of the current iterator. This is because of limitations of Go generics. To apply a mapping that changes the type, see the iterator.Map2 function.
func (DefaultIterator2[K, V]) Take2 ¶ added in v0.20.0
func (di2 DefaultIterator2[K, V]) Take2(n int) Iterator2[K, V]
Take2 returns a variant of the current iterator that which returns at most n pairs of elements. If the current iterator has less than or exactly n element pairs, the returned iterator is equivalent to the input iterator.
type DefaultMutableIterator ¶ added in v0.20.0
type DefaultMutableIterator[T any] struct { CoreMutableIterator[T] DefaultIterator[T] }
DefaultMutableIterator wraps a CoreMutableIterator together with a DefaultIterator to provide and implementation of MutableIterator.
func NewDefaultMutableIterator ¶ added in v0.20.0
func NewDefaultMutableIterator[T any](citr CoreMutableIterator[T]) DefaultMutableIterator[T]
NewDefaultMutableIterator builds a MutableIterator from a CoreMutableIterator by adding the methods of IteratorExtensions.
type DefaultMutableIterator2 ¶ added in v0.20.0
type DefaultMutableIterator2[K any, V any] struct { CoreMutableIterator2[K, V] DefaultIterator2[K, V] }
DefaultMutableIterator2 wraps a CoreMutableIterator together with a DefaultIterator to provide and implementation of MutableIterator.
func NewDefaultMutableIterator2 ¶ added in v0.20.0
func NewDefaultMutableIterator2[K any, V any](citr CoreMutableIterator2[K, V]) DefaultMutableIterator2[K, V]
type Generator ¶ added in v0.16.0
Generator is a function taking a Consumer. The function is expected to yield values to the consumer.
type GeneratorPanic ¶
type GeneratorPanic struct {
// contains filtered or unexported fields
}
GeneratorPanic is an error type indicating that a generator iterator function has panicked
func (GeneratorPanic) Error ¶
func (pp GeneratorPanic) Error() string
func (GeneratorPanic) Unwrap ¶
func (pp GeneratorPanic) Unwrap() error
type Iterator ¶
type Iterator[T any] interface { CoreIterator[T] IteratorExtensions[T] }
Iterator is a generic iterator type, facilitating iteration over single elements of a generic type plus some utility methods. It consists of methods from CoreIterator, plus the ones from IteratorExtensions.
func AsKV ¶ added in v0.20.0
func AsKV[K any, V any](iter2 CoreIterator2[K, V]) Iterator[KeyValue[K, V]]
AsKV takes a CoreIterator2 and returns an Iterator where each value is a KeyValue pair.
func Filter ¶
func Filter[T any](iter CoreIterator[T], predicate func(T) bool) Iterator[T]
Filter applies a filter function predicate of type func(T) bool, producing a new iterator containing only the elements that satisfy the function.
func FilterMap ¶
func FilterMap[T, U any](iter CoreIterator[T], mapping func(T) (U, bool)) Iterator[U]
FilterMap applies both transformation and filtering logic to an Iterator. The function mapping is applied to each value of type T, producing either a new value of type U and a true boolean, or undefined value and a false boolean. Values are taken from the value when the boolean is true to produce a new Iterator; returns when the boolean is false are ignored.
func FilterMapOpt ¶ added in v0.20.0
FilterMapOpt applies both transformation and filtering logic to an iterator. The function mapping is applied to each element of type T, producing either an option value of type U or an empty option. The result is an iterator over U drawn from only the non-empty options returned.
func FilterValues ¶ added in v0.16.0
func FilterValues[T any](iter CoreIterator[result.Result[T]]) Iterator[T]
FilterValues takes an iterator of results and returns an iterator of the underlying result value type for only those results that have no error.
func Generate ¶
Generate creates an Iterator from a Generator function. A Consumer is created and passed to the function. The function is run in a separate goroutine, and its yielded values are sent over a channel to the iterator where they may be consumed in an iterative way by calls to Next() and Value(). Alternatively, the channel itself is available via the Chan() method. A call to Abort() will cause the channel to close and no further elements will be produced by Next() or a read of the channel. Any attempt to subsequently yield a value in the generator will cause it to terminate, via an AbortGenerator panic.
func GenerateResults ¶
func GenerateResults[T any](generator ResultGenerator[T]) Iterator[result.Result[T]]
GenerateResults is a variation on Generate that produces an iterator of result types. If the generator function panics, an error result of type GeneratorPanic is produced prior to closing the consumer channel.
func IncRange ¶ added in v0.18.0
Range creates an iterator that produces a sequence of numeric values that range between from and upto inclusive. This sequence may be descending if upto is less than from. If from == upto, an iterator yielding a single value is returned.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
i := iterator.IncRange(0, 5)
for e := range i.Seq() {
fmt.Println(e)
}
}
Output: 0 1 2 3 4 5
Example (Single) ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
i := iterator.IncRange(0, 0)
for e := range i.Seq() {
fmt.Println(e)
}
}
Output: 0
func IncRangeBy ¶ added in v0.18.0
RangeBy creates an iterator that produces a sequence of numeric values that range between from and upto inclusive, with a difference between each value of by. The value of by can be negative, in which case upto should be less than from, but it cannot be zero unless from == upto, in which case an iterator yielding a single value is returned.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
i := iterator.IncRangeBy(0, 4, 2)
for e := range i.Seq() {
fmt.Println(e)
}
}
Output: 0 2 4
func MakeIterator
deprecated
added in
v0.16.0
func MakeIterator[T any](base SimpleIterator[T]) Iterator[T]
MakeIterator creates a generic iterator from a simple iterator. Provides an implementation of additional Iterator methods.
Deprecated: use NewFromSimple
func Map ¶
func Map[T any, U any](iter CoreIterator[T], mapping func(T) U) Iterator[U]
Map applies function mapping of type func(T) U to each value, producing a new iterator over U.
func New ¶ added in v0.20.0
New builds an Iterator from a standard library iter.Seq
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
// fib returns a native Go iterator (fibonacci sequence).
fib := func(yield func(int) bool) {
tail := [2]int{0, 1}
for {
if !yield(tail[1]) {
return
}
tail[0], tail[1] = tail[1], tail[0]+tail[1]
}
}
fibItr := iterator.New(fib) // iterator.Iterator[int]
fibSeq := fibItr.Seq() // iter.Seq[int]
i := 0
const max = 5
for f := range fibSeq {
if i > max {
break
}
fmt.Println(f)
i++
}
// Output
// 1
// 1
// 2
// 3
// 5
}
Output:
func NewFromSimple ¶ added in v0.20.0
func NewFromSimple[T any](simple SimpleIterator[T]) Iterator[T]
NewFromSimple builds an Iterator from a SimpleIterator.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
// counter is a SimpleIterator implementation that produces an
// infinite string of integers, starting from 0.
type counter struct {
value int
count int
aborted bool
}
// Next sets value to the next count, increments the count, and
// returns true, unless aborted. When aborted, it is a no-op.
func (c *counter) Next() bool {
if c.aborted {
return false
} else {
c.value = c.count
c.count++
return true
}
}
// Value returns the current value.
func (c *counter) Value() int {
return c.value
}
// Abort stops the iterator by setting the aborted flag.
func (c *counter) Abort() {
c.aborted = true
}
// Reset sets the counter back to 0.
func (c *counter) Reset() {
c.count = 0
}
func main() {
i := iterator.NewFromSimple(&counter{})
c := i.Take(10).Collect()
fmt.Println(c)
}
Output: [0 1 2 3 4 5 6 7 8 9]
func NewFromSimpleWithSize ¶ added in v0.20.0
func NewFromSimpleWithSize[T any](simple SimpleIterator[T], size func() IteratorSize) Iterator[T]
NewFromSimpleWithSize builds an Iterator from a SimpleIterator plus a function that returns the number of items left in the iterator.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
// counter is a SimpleIterator implementation that produces an
// infinite string of integers, starting from 0.
type counter struct {
value int
count int
aborted bool
}
// Next sets value to the next count, increments the count, and
// returns true, unless aborted. When aborted, it is a no-op.
func (c *counter) Next() bool {
if c.aborted {
return false
} else {
c.value = c.count
c.count++
return true
}
}
// Value returns the current value.
func (c *counter) Value() int {
return c.value
}
// Abort stops the iterator by setting the aborted flag.
func (c *counter) Abort() {
c.aborted = true
}
// Reset sets the counter back to 0.
func (c *counter) Reset() {
c.count = 0
}
func main() {
i := iterator.NewFromSimpleWithSize(&counter{},
func() iterator.IteratorSize { return iterator.SIZE_INFINITE })
func() {
defer func() { fmt.Println(recover()) }()
i.Collect() // Attempting to collect the infinite iterator will panic.
}()
c := i.Take(10).Collect() // Collecting only the first 10 elements succeeds.
fmt.Println(c)
}
Output: cannot consume an infinite iterator [0 1 2 3 4 5 6 7 8 9]
func NewWithSize ¶ added in v0.20.0
func NewWithSize[T any](seq iter.Seq[T], size func() IteratorSize) Iterator[T]
New builds an Iterator from a standard library iter.Seq plus a function that returns the number of items left in the iterator.
func Of ¶
Of makes an Iterator[T] containing the variadic arguments of type T
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
itr := iterator.Of("one", "two", "three")
fmt.Println(itr.Size().Size)
for e := range itr.Seq() {
fmt.Println(e)
}
}
Output: 3 one two three
func Range ¶
Range creates an iterator that produces a sequence of numeric values that range between from and upto exclusive. This sequence may be descending if upto is less than from. If from == upto, an empty iterator is returned.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
i := iterator.Range(0, 5)
for e := range i.Seq() {
fmt.Println(e)
}
}
Output: 0 1 2 3 4
Example (Descending) ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
i := iterator.Range(5, 0)
for e := range i.Seq() {
fmt.Println(e)
}
}
Output: 5 4 3 2 1
Example (Empty) ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
c := iterator.Range(0, 0).Collect()
fmt.Printf("%#v", c)
}
Output: []int{}
func RangeBy ¶
RangeBy creates an iterator that produces a sequence of numeric values that range between from and upto exclusive, with a difference between each value of by. The value of by can be negative, in which case upto should be less than from, but it cannot be zero unless from == upto, in which case an empty iterator is returned.
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
i := iterator.RangeBy(0, 5, 2)
for e := range i.Seq() {
fmt.Println(e)
}
}
Output: 0 2 4
func Take ¶ added in v0.16.0
func Take[T any](n int, iter CoreIterator[T]) Iterator[T]
Take transforms a CoreIterator into an Iterator that returns at most n elements of the original iterator. Note that any Iterator is also a CoreIterator. If there are less than or exactly n elements available, the returned iterator is equivalent to the input iterator.
type Iterator2 ¶ added in v0.20.0
type Iterator2[K any, V any] interface { CoreIterator2[K, V] IteratorExtensions[V] Iterator2Extensions[K, V] }
Iterator2 is a generic iterator type, facilitating iteration over pairs of elements of different generic types. One of these is the "value", and the other is the "key" which may be something like a map key or slice index. It also has some utility methods. It consists of methods from CoreIterator2, IteratorExtensions and Iterator2Extensions.
func Enumerate ¶ added in v0.20.0
func Enumerate[T any](itr CoreIterator[T]) Iterator2[int, T]
Enumerate takes a CoreIterator and builds an Iterator2 that returns the pair of the index of each element (starting at zero) and the original element.
func Filter2 ¶ added in v0.20.0
func Filter2[K, V any](iter CoreIterator2[K, V], predicate func(K, V) bool) Iterator2[K, V]
Filter2 applies a filter function of type func(K, V) bool over each key and value pair, producing a new iterator containing only the elements that satisfy the function.
func FilterMap2 ¶ added in v0.20.0
func FilterMap2[K, V, X, Y any](iter CoreIterator2[K, V], mapping func(K, V) (X, Y, bool)) Iterator2[X, Y]
FilterMap2 applies both transformation and filtering logic to an Iterator2. The function mapping is applied to each key and value pair, of type K and V respectively, producing either a new key and value pairs (of type X and Y) and a true boolean, or undefined key and value and a false boolean. Values are taken from the keys and values when the boolean is true to produce a new Iterator2.
func Map2 ¶ added in v0.20.0
func Map2[K, V, X, Y any](iter CoreIterator2[K, V], mapping func(K, V) (X, Y)) Iterator2[X, Y]
Map2 applies function mapping of type func(K, V) (X,Y) to each key and value pair, producing a new Iterator2 over X and Y.
func New2 ¶ added in v0.20.0
New2 creates an Iterator2 from a standard library iter.Seq2. Iterator Size is unknown.
func New2WithSize ¶ added in v0.20.0
New2WithSize creates an Iterator2 from a standard library iter.Seq2 and a size function that returns the remaining items in the iterator.
func Take2 ¶ added in v0.20.0
func Take2[K any, V any](n int, iter CoreIterator2[K, V]) Iterator2[K, V]
Take2 transforms a CoreIterator2 into an Iterator2 that returns at most n pairs of elements. Note that any Iterator2 is also a CoreIterator2. If there are less than or exactly n elements available, the returned iterator is equivalent to the input iterator.
type Iterator2Extensions ¶ added in v0.20.0
type Iterator2Extensions[K any, V any] interface { // Collect2 collects all the element pairs from the iterator into a slice of // KeyValue objects. Collect2() []KeyValue[K, V] // Collect2Into collects all the element pairs from the iterator into the // slice of KeyValue objects pointed to by s. The final slice is returned. Collect2Into(s *[]KeyValue[K, V]) []KeyValue[K, V] // Collect2IntoCap collects all the element pairs from the iterator into the // slice of KeyValue objects pointed to by s, up to but not exceeding the // capacity of *s. The final slice is returned. Collect2IntoCap(s *[]KeyValue[K, V]) []KeyValue[K, V] // Chan2 returns the iterator as a channel of KeyValue objects. The iterator // is consumed in a goroutine which yields results to the channel. Chan2() <-chan KeyValue[K, V] // Filter2 is a filtering method that creates a new iterator which contains // a subset of element pairs contained by the current one. This function // takes a predicate function p and only element pairs for which this // function returns true should be included in the filtered iterator. Filter2(p func(K, V) bool) Iterator2[K, V] // Morph2 is a mapping function that creates a new iterator which contains // pairs of elements of the current iterator with the supplied function m // applied to each key and value. The type of the return value and key of m // must be of the same type as the kay and value of the current iterator. // This is because of limitations of Go generics. To apply a mapping that // changes the type, see the [iterator.Map2] function. Morph2(m func(K, V) (K, V)) Iterator2[K, V] // FilterMorph2 is a filtering and mapping method that creates a new // iterator from an existing one by simultaneously transforming and // filtering each iterator element pair. The method takes a mapping function // f that transforms and filters each element pair. It does this by taking // an input element key and value and returning a new element key and value // and a boolean flag. Only elements for which this flag is true are // included in the new iterator. E.g. // inputMap := map[int]int{0: 2, 1: 4, 2: 6, 3: 8} // itr := maps.Iter(inputMap).FilterMorph2(func(k, v int) (int, int, bool) { // return k + 1, v * 2, (k+v)%2 == 0 // }) // output := iterator.CollectMap(itr) // map[int]int{1: 4, 3: 12} // Note that this function is not able to map element keys or values to // different types due to limitations of Go generics. For a filter mapping // function that can map to different types, see the [iterator.FilterMap2] // function. FilterMorph2(f func(K, V) (K, V, bool)) Iterator2[K, V] // Take2 returns a variant of the current iterator that which returns at // most n pairs of elements. If the current iterator has less than or // exactly n element pairs, the returned iterator is equivalent to the input // iterator. Take2(int) Iterator2[K, V] }
Iterator2Extensions defines additional iterator methods that are specific to Iterator2.
type IteratorExtensions ¶ added in v0.20.0
type IteratorExtensions[T any] interface { // Chan returns the iterator as a channel. Chan() <-chan T // Collect collects all elements from the iterator into a slice. Collect() []T // CollectInto adds all elements from the iterator into an existing slice. CollectInto(*[]T) []T // CollectIntoCap add elements from the iterator into an existing slice // until either the capacity of the slice is filled, or the iterator is // exhausted, which ever is first. CollectIntoCap(*[]T) []T // Enumerate returns an iterator that enumerates the elements of this // iterator, returning an Iterator2 of the index and the value. Enumerate() Iterator2[int, T] // Filter is a filtering method that creates a new iterator which contains a // subset of elements contained in the current one. This function takes a // predicate function p and only elements for which this function returns // true should be included in the filtered iterator. Filter(p func(T) bool) Iterator[T] // Morph is a mapping function that creates a new iterator which contains // the elements of the current iterator with the supplied function m applied // to each one. The type of the return value of m must be the same as that // of the elements of the current iterator. This is because of limitations // of Go generics. To apply a mapping that changes the type, see the // [iterator.Map] function. Morph(m func(T) T) Iterator[T] // FilterMorph is a filtering and mapping method that creates a new iterator // from an existing one by simultaneously transforming and filtering each // iterator element. The method takes a mapping function f that transforms // and filters each element. It does this by taking an input element value // and returning a new element value and a boolean flag. Only elements for // which this flag is true are included in the new iterator. E.g. // itr := iterator.Of(0,1,2,3,4) // itrMorph := itr.FilterMorph(func(v int) (int, bool) { return v*2, v%2 == 0}) // result := itrMorph.Collect() // []int{0,4,8} // Note that this function is not able to map elements to values of a // different type due to limitations of Go generics. For a filter mapping // function that can change the type, see the [iterator.FilterMap] function. FilterMorph(f func(T) (T, bool)) Iterator[T] // Take returns a variant of the current iterator that which returns at most // n elements. If the current iterator has less than or exactly n elements, // the returned iterator is equivalent to the input iterator. Take(n int) Iterator[T] // Any returns true if p returns true for at least one element in the iterator. Any(p func(T) bool) bool // All returns true if p returns true for all the elements in the iterator. All(p func(T) bool) bool // Fold1 combines the elements of the iterator into a single value using an // accumulation function. It takes an initial value init and an accumulation // function f. The iterator must have at least one element, or this method will // panic with [ErrEmptyIterator]. If there is only one element, this element be // returned. Otherwise, the first two elements are fed into the accumulation // function f. The result of this is combined with the next element to get the // next result and so on until the iterator is consumed. The final result is // returned. If the iterator is known to be of infinite size, this method will // panic with [ErrSizeInfinite]. Fold1(f func(a, e T) T) T // Fold combines the elements of the iterator into a single value using an // accumulation function. It takes an initial value init and the accumulation // function f. If the iterator is empty, init is returned. Otherwise the initial // value is fed into the accumulation function f along with the first element // from the iterator. The result is then fed back into f along with the second // element, and so on until the iterator is consumed. The final result is the // final value returned by the function. If the iterator is known to be of // infinite size, this method will panic with [ErrSizeInfinite]. Fold(init T, f func(a, e T) T) T // Intercalate1 is a variation on [Fold1] which combines the elements of the // iterator into a single value using an accumulation function and an // interspersed value. The iterator must have at least one element, otherwise it // will panic with [ErrEmptyIterator]. The accumulated result is initially set // to the first element, and is combined with subsequent elements as follows: // // acc = f(f(acc,inter),e) // // where acc is he accumulated value, e is the next element and inter is the // inter parameter. The final value of acc will be the value returned. If the // iterator is known to be of infinite size, this function will panic with // [ErrSizeInfinite]. Intercalate1(inter T, f func(a, e T) T) T // Intercalate is a variation on [Fold] which combines the elements of the // iterator into a single value using an accumulation function and an // interspersed value. If the iterator has no elements, the empty parameter is // returned. Otherwise, the accumulated result is initially set to the first // element, and is combined with subsequent elements as follows: // // acc = f(f(acc,inter),e) // // where acc is he accumulated value, e is the next element and inter is the // inter parameter, and the final value of acc will be the value returned. If // the iterator is known to be of infinite size, this function will panic with // [ErrSizeInfinite]. Intercalate(empty T, inter T, f func(a, e T) T) T }
IteratorExtensions defines methods available to all iterators beyond the core functionality provided by CoreIterator.
type IteratorSize ¶
type IteratorSize struct {
Type IteratorSizeType
Size int
}
IteratorSize holds iterator sizing information
var ( SIZE_UNKNOWN IteratorSize = IteratorSize{Type: SizeUnknown} SIZE_INFINITE = IteratorSize{Type: SizeInfinite, Size: -1} )
func NewSize ¶ added in v0.16.0
func NewSize(n int) IteratorSize
NewSize creates an IteratorSize implementation that has a fixed size of n.
func NewSizeInfinite ¶ added in v0.20.0
func NewSizeInfinite() IteratorSize
func NewSizeMax ¶ added in v0.20.0
func NewSizeMax(n int) IteratorSize
NewSizeMax creates an IteratorSize implementation that has a size no more than n.
func NewSizeUnknown ¶ added in v0.20.0
func NewSizeUnknown() IteratorSize
Iterator sizing information; size is unknown
func (IteratorSize) Allocate ¶
func (isz IteratorSize) Allocate() int
Allocate returns an estimated allocation size needed to accommodate the remaining elements in the iterator. If the iterator size is infinite, the function will panic with iterator.ErrAllocationSizeInfinite.
func (IteratorSize) IsInfinite ¶ added in v0.20.0
func (size IteratorSize) IsInfinite() bool
func (IteratorSize) IsKnown ¶ added in v0.20.0
func (size IteratorSize) IsKnown() bool
IsKnown returns true if the iterator size is one whose actual size is known.
func (IteratorSize) IsKnownToBe ¶ added in v0.20.0
func (size IteratorSize) IsKnownToBe(n int) bool
IsKnownToBe returns true if the iterator size is one whose actual size is known, and is equal to the given value.
func (IteratorSize) IsMaxKnown ¶ added in v0.20.0
func (size IteratorSize) IsMaxKnown() bool
IsMaxKnown returns true if the iterator size is one whose maximum size is known.
func (IteratorSize) IsMaxKnownToBe ¶ added in v0.20.0
func (size IteratorSize) IsMaxKnownToBe(n int) bool
IsMaxKnownToBe returns true if the iterator size is one whose maximum size is known, and is equal to the given value.
func (IteratorSize) IsUnknown ¶ added in v0.20.0
func (size IteratorSize) IsUnknown() bool
IsUnknown returns true if the given IteratorSize instance represents an unknown size
func (IteratorSize) Subset ¶ added in v0.16.0
func (isz IteratorSize) Subset() IteratorSize
Subset is used to transform an IteratorSize to one which is a subset of the current one. Given an iterator A whose size is described by the current IteratorSize, this functions returns a size corresponding to the number of elements in iterator B, where iterator B contains no more than the number of elements of iterator A.
type IteratorSizeType ¶ added in v0.20.0
type IteratorSizeType int
const ( SizeUnknown IteratorSizeType = iota // SizeUnknown represents an unknown size. SizeKnown // SizeKnown represents a completely known size. SizeAtMost // SizeAtMost represents a number of elements whose upper limit is known. SizeInfinite // SizeInfinite represents the knowledge that an iterator will not end. )
type KeyValue ¶ added in v0.20.0
KeyValue holds a key value pair
func Collect2 ¶ added in v0.20.0
func Collect2[K any, V any](itr CoreIterator2[K, V]) []KeyValue[K, V]
Collect2 collects all elements from an Iterator2 into a slice of KeyValue pairs. If the iterator is known to be of infinite size, this function will panic.
func Collect2Into ¶ added in v0.20.0
func Collect2Into[K any, V any](iter CoreIterator2[K, V], slice *[]KeyValue[K, V]) []KeyValue[K, V]
Collect2Into collects all element pairs from an Iterator2 into a slice of KeyValue pairs, a pointer to which is passed. Pairs are appended to any existing data in the slice. The slice referenced may be reallocated as the append function is used to add pairs to the slice. The slice may be a nil slice. For convenience, the final slice is returned. If the iterator is known to have an infinite size, this function will panic.
func Collect2IntoCap ¶ added in v0.20.0
func Collect2IntoCap[K any, V any](iter CoreIterator2[K, V], slice *[]KeyValue[K, V]) []KeyValue[K, V]
Collect2IntoCap collects all element pairs from an Iterator2 into a slice of KeyValue pairs, a pointer to which is passed. Pairs are appended to any existing data in the slice. The slice referenced may be reallocated as the append function is used to add pairs to the slice. The slice may be a nil slice. For convenience, the final slice is returned. If the iterator is known to have an infinite size, this function will panic.
type MutableIterator ¶ added in v0.20.0
type MutableIterator[T any] interface { CoreMutableIterator[T] IteratorExtensions[T] }
MutableIterator is a generic iterator type, facilitating iteration over single elements of a generic type that also supports mutation of the underlying value. Elements can be modified in place or removed from their underlying collection. This type also includes some utility methods. It consists of methods from CoreMutableIterator, plus the ones from IteratorExtensions.
func MutSlice
deprecated
added in
v0.20.0
func MutSlice[T any](slice *[]T) MutableIterator[T]
MutSlice makes a MutableIterator[T] from slice []T, containing all the elements from the slice in order.
Deprecated: use slices.IterMut()
func NewFromSimpleMutable ¶ added in v0.20.0
func NewFromSimpleMutable[T any](itr SimpleMutableIterator[T]) MutableIterator[T]
NewFromSimpleMutable builds a MutableIterator from a SimpleMutableIterator.
func NewFromSimpleMutableWithSize ¶ added in v0.20.0
func NewFromSimpleMutableWithSize[T any](itr SimpleMutableIterator[T], size func() IteratorSize) MutableIterator[T]
NewFromSimpleMutableWithSize builds a MutableIterator from a SimpleMutableIterator and a size function that returns the number of items remaining items in the iterator.
type MutableIterator2 ¶ added in v0.20.0
type MutableIterator2[K any, V any] interface { CoreMutableIterator2[K, V] IteratorExtensions[V] Iterator2Extensions[K, V] }
MutableIterator2 is a generic iterator type, facilitating iteration over pairs of elements of different generic types. One of these is the "value", and the other is the "key" which may be something like a map key or slice index. Two mutation operations are supported; the modification of the the "value" element, and removal of the element pair from the underlying collection. It also has some utility methods. It consists of methods from CoreIterator2, IteratorExtensions and Iterator2Extensions.
type ResultConsumer ¶ added in v0.16.0
ResultConsumer is a variation on `Consumer` which is used to yield only result types. It adds dedicated methods to yield non-error values and errors.
func (*ResultConsumer[T]) Yield ¶ added in v0.16.0
func (yr *ResultConsumer[T]) Yield(value result.Result[T])
Yield yields the next result to the result consumer
func (*ResultConsumer[T]) YieldError ¶ added in v0.16.0
func (yr *ResultConsumer[T]) YieldError(err error)
YieldError yields an error to the consumer
func (*ResultConsumer[T]) YieldValue ¶ added in v0.16.0
func (yr *ResultConsumer[T]) YieldValue(value T)
YieldValue yields the next successful value to the consumer
type ResultGenerator ¶ added in v0.16.0
type ResultGenerator[T any] func(ResultConsumer[T]) error
ResultGenerator is a function taking a ResultConsumer object to which results may be yielded. If a non-nil error is returned, it will be yielded as an error result.
type SeqCoreIterator ¶ added in v0.20.0
type SeqCoreIterator[T any] struct { // contains filtered or unexported fields }
SeqCoreIterator wraps an iter.Seq iterator, plus an optional size function, providing methods to implement CoreIterator.
func NewSeqCoreIterator ¶ added in v0.20.0
func NewSeqCoreIterator[T any](seq iter.Seq[T]) *SeqCoreIterator[T]
NewSeqCoreIterator builds a CoreIterator from a standard library iter.Seq
func NewSeqCoreIteratorWithSize ¶ added in v0.20.0
func NewSeqCoreIteratorWithSize[T any](seq iter.Seq[T], size func() IteratorSize) *SeqCoreIterator[T]
NewSeqCoreIterator builds a CoreIterator from a standard library iter.Seq and a function that returns the number of items in the iterator.
func (*SeqCoreIterator[T]) Abort ¶ added in v0.20.0
func (si *SeqCoreIterator[T]) Abort()
func (*SeqCoreIterator[T]) Next ¶ added in v0.20.0
func (si *SeqCoreIterator[T]) Next() (ok bool)
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
for itr := iterator.Range(0, 5); itr.Next(); {
fmt.Printf("%d\n", itr.Value())
}
}
Output: 0 1 2 3 4
func (*SeqCoreIterator[T]) Reset ¶ added in v0.20.0
func (si *SeqCoreIterator[T]) Reset()
Reset restarts the iterator
func (*SeqCoreIterator[T]) Seq ¶ added in v0.20.0
func (si *SeqCoreIterator[T]) Seq() iter.Seq[T]
func (*SeqCoreIterator[T]) SeqOK ¶ added in v0.20.0
func (si *SeqCoreIterator[T]) SeqOK() bool
func (*SeqCoreIterator[T]) Size ¶ added in v0.20.0
func (si *SeqCoreIterator[T]) Size() IteratorSize
func (*SeqCoreIterator[T]) Value ¶ added in v0.20.0
func (si *SeqCoreIterator[T]) Value() T
type SeqCoreIterator2 ¶ added in v0.20.0
type SeqCoreIterator2[K any, V any] struct { *SeqCoreIterator[V] // contains filtered or unexported fields }
SeqCoreIterator2 wraps an iter.Seq2, providing methods to implement CoreIterator2
func NewSeqCoreIterator2 ¶ added in v0.20.0
func NewSeqCoreIterator2[K any, V any](seq2 iter.Seq2[K, V]) *SeqCoreIterator2[K, V]
NewSeqCoreIterator2 builds a CoreIterator2 implementation from an iter.Seq2 iterator
func NewSeqCoreIterator2WithSize ¶ added in v0.20.0
func NewSeqCoreIterator2WithSize[K any, V any](seq2 iter.Seq2[K, V], size func() IteratorSize) *SeqCoreIterator2[K, V]
NewSeqCoreIterator2WithSize builds a CoreIterator2 implementation from an iter.Seq2 and a function that returns the size of the remaining items in the iterator.
func (*SeqCoreIterator2[K, V]) Key ¶ added in v0.20.0
func (si *SeqCoreIterator2[K, V]) Key() K
func (*SeqCoreIterator2[K, V]) Seq2 ¶ added in v0.20.0
func (si *SeqCoreIterator2[K, V]) Seq2() iter.Seq2[K, V]
type SeqCoreMutableIterator2 ¶ added in v0.20.0
type SeqCoreMutableIterator2[K any, V any] struct { SeqCoreIterator2[K, V] // contains filtered or unexported fields }
func NewSeqCoreMutableIterator2 ¶ added in v0.20.0
func NewSeqCoreMutableIterator2[K any, V any](seq2 iter.Seq2[K, V], delete func(), set func(V)) *SeqCoreMutableIterator2[K, V]
func NewSeqCoreMutableIterator2WithSize ¶ added in v0.20.0
func NewSeqCoreMutableIterator2WithSize[K any, V any](seq2 iter.Seq2[K, V], delete func(), set func(V), size func() IteratorSize) *SeqCoreMutableIterator2[K, V]
func (*SeqCoreMutableIterator2[K, V]) Delete ¶ added in v0.20.0
func (smi *SeqCoreMutableIterator2[K, V]) Delete()
func (*SeqCoreMutableIterator2[K, V]) Set ¶ added in v0.20.0
func (smi *SeqCoreMutableIterator2[K, V]) Set(v V)
type SimpleCoreIterator ¶ added in v0.20.0
type SimpleCoreIterator[T any] struct { SimpleIterator[T] // contains filtered or unexported fields }
SimpleCoreIterator wraps a SimpleIterator and provides methods to implement CoreIterator
func NewSimpleCoreIterator ¶ added in v0.20.0
func NewSimpleCoreIterator[T any](itr SimpleIterator[T]) *SimpleCoreIterator[T]
NewSimpleCoreIterator builds a CoreIterator from a SimpleIterator
func NewSimpleCoreIteratorWithSize ¶ added in v0.20.0
func NewSimpleCoreIteratorWithSize[T any](itr SimpleIterator[T], size func() IteratorSize) *SimpleCoreIterator[T]
NewSimpleCoreIteratorWithSize builds a CoreIterator from a SimpleIterator plus a function that returns the remaining number of items in the iterator.
func (*SimpleCoreIterator[T]) Seq ¶ added in v0.20.0
func (itr *SimpleCoreIterator[T]) Seq() iter.Seq[T]
Example ¶
package main
import (
"fmt"
"github.com/robdavid/genutil-go/iterator"
)
func main() {
for n := range iterator.Range(0, 5).Seq() {
fmt.Printf("%d\n", n)
}
}
Output: 0 1 2 3 4
func (*SimpleCoreIterator[T]) SeqOK ¶ added in v0.20.0
func (itr *SimpleCoreIterator[T]) SeqOK() bool
func (*SimpleCoreIterator[T]) Size ¶ added in v0.20.0
func (itr *SimpleCoreIterator[T]) Size() IteratorSize
type SimpleCoreMutableIterator ¶ added in v0.20.0
type SimpleCoreMutableIterator[T any] struct { SimpleMutableIterator[T] // contains filtered or unexported fields }
SimpleCoreMutableIterator wraps a SimpleMutableIterator and provides methods to implement CoreMutableIterator
func NewSimpleCoreMutableIterator ¶ added in v0.20.0
func NewSimpleCoreMutableIterator[T any](itr SimpleMutableIterator[T]) *SimpleCoreMutableIterator[T]
NewSimpleCoreMutableIterator builds a CoreMutableIterator from a SimpleMutableIterator.
func NewSimpleCoreMutableIteratorWithSize ¶ added in v0.20.0
func NewSimpleCoreMutableIteratorWithSize[T any](itr SimpleMutableIterator[T], size func() IteratorSize) *SimpleCoreMutableIterator[T]
NewSimpleCoreMutableIterator builds a CoreMutableIterator from a SimpleMutableIterator plus a function that returns the number of items remaining in the iterator.
func (*SimpleCoreMutableIterator[T]) Seq ¶ added in v0.20.0
func (si *SimpleCoreMutableIterator[T]) Seq() iter.Seq[T]
func (*SimpleCoreMutableIterator[T]) SeqOK ¶ added in v0.20.0
func (itr *SimpleCoreMutableIterator[T]) SeqOK() bool
func (*SimpleCoreMutableIterator[T]) Size ¶ added in v0.20.0
func (itr *SimpleCoreMutableIterator[T]) Size() IteratorSize
type SimpleIterator ¶ added in v0.16.0
type SimpleIterator[T any] interface { // Next sets the iterator's current value to be the first, and subsequent, // iterator elements. False is returned only when there are no more elements // (the current value remains unchanged). Next() bool // Value gets the current iterator value. Value() T // Abort stops the iterator; subsequent calls to Next() will return false. Abort() // Reset stops the iterator; subsequent calls to Next() will begin the // iterator from the start. Note not all iterators are guaranteed to return // the same sequence again, for example iterators that perform IO may not // read the same data again, or may return no data at all. Reset() }
SimpleIterator defines a core set of methods for iterating over a collection of elements, of type T. More complete iterator implementations can be built on this core set of methods.
type SimpleMutableIterator ¶ added in v0.20.0
type SimpleMutableIterator[T any] interface { SimpleIterator[T] // Set modifies a value in place in the underlying collection. Set(T) // Delete deletes the current value, which must be the last value returned // by Next(). This function may not be implemented for all iterator types, // in which case it will return an [ErrDeleteNotImplemented] error. Delete() }
SimpleMutableIterator extends SimpleIterator by adding methods to support element mutation. More complete MutableIterator implementations can be built on this core set of methods.