iter

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2023 License: MIT Imports: 5 Imported by: 0

README

iter Go Reference

A generic Go iterator library inspired by Rust's std::iter::Iterator

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

Installation

Requires: Go 1.18+

go get github.com/rodaine/iter

Limitations

Go's generics are powerful, but still limited. This affects the ergonomics of some usecases. The common thread in all cases is that methods must be fully instantiated/monomorphized at compile-time.

Methods cannot have type parameters

Associated Issue: golang/go#49085

Because methods cannot have type parameters (beyond the types defined on the receiver type), operations that would map types cannot be implemented as methods. This makes Map, Fold, and others not currently chainable; however, they have been implemented as free functions:

// WANT
// func (iter Iterator[A]) Map[B any](fn MapFunc[A, B]) Iterator[B] { ... }

FromItems(1, 2, 3).
  Map(strconv.Itoa).
  ToSlice() // ["1", "2", "3"]
  
// GOT
// func Map[A, B any](iter Iterator[A], fn MapFunc[A, B]) Iterator[B] { ... }

Map(
  FromItems(1, 2, 3), 
  strconv.Itoa,
).ToSlice() // ["1", "2", "3"]
Types/Methods cannot cause an instantiation cycle

Associated Issue: golang/go#50215

When a type is instantiated in Go, all its methods must also be instantiated at compile time, even if that method is not necessarily used. This is required as methods may be called dynamically via interface assertions or reflection. For Enumerate, which maps an Iterator[E] to Iterator[Pair[int, E]], defining this as a method would require for the compiler to also instantiate Iterator[Pair[int, Pair[int, E]]], and so on infinitely. This does work as a free function, however.

// WANT
// func (iter Iterator[A]) Enumerate() Iterator[Pair[A, B]] { ... }

FromItems('a', 'b', 'c').
  Enumerate().
  ToSlice() // [{0, 'a'}, {1, 'b'}, {2, 'c'}]
  
// GOT
// func Enumerate[A](iter Iterator[A]) Iterator[Pair[int, A]] { ... }

Enumerate(
  FromItems('a', 'b', 'c'),
).ToSlice() // [{0, 'a'}, {1, 'b'}, {2, 'c'}]
Specialization is not supported

Certain functionality, such as Sum and Equality, require specializations or narrowing of the generic types to work. Go generics currently do not support specialization of methods, but it can be achieved with free functions.

// WANT
// func (iter Iterator[N Number]) Sum() N { ... }

FromItems(1, 2, 3).
  Sum() // 6

// GOT
// func Sum[N Number](iter Iterator[N]) N { ... }

Sum(
  FromItems(1, 2, 3),
) // 6

Performance

The performance characteristics of this module have not yet been evaluated.

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fold

func Fold[S, E any](iter Iterator[E], initial S, fn FoldFunc[S, E]) S

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

func MaxByKey[E any, K constraints.Ordered](iter Iterator[E], fn KeyFunc[E, K]) (E, bool)

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

func MinByKey[E any, K constraints.Ordered](iter Iterator[E], fn KeyFunc[E, K]) (E, bool)

MinByKey consumes the provided Iterator, returning the minimum value described by the value returned by the specified KeyFunc.

func Product

func Product[N Number](iter Iterator[N]) (product N)

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

func Sum[N Number](iter Iterator[N]) (sum N)

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

type CompareFunc[T any] func(a, b T) Equality

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

type CoreFunc[E any] func() (next E, ok bool)

CoreFunc is a convenience type for implementing Core for a function that matches the signature of Core.Next.

func (CoreFunc[E]) Next

func (cf CoreFunc[E]) Next() (next E, ok bool)

Next satisfies the Core interface.

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

func CompareByKey[E any, K constraints.Ordered](a, b Iterator[E], fn KeyFunc[E, K]) Equality

CompareByKey lexicographically compares two iterators element-by-element based off the Equality of the values returned by the provided KeyFunc.

func (Equality) String

func (e Equality) String() string

String satisfies the fmt.Stringer interface

type FilterMapFunc

type FilterMapFunc[A, B any] func(from A) (to B, ok bool)

FilterMapFunc converts a value of type A into B, returning ok as true if the value should be emitted.

type FlatMapFunc

type FlatMapFunc[A, B any] MapFunc[A, Iterator[B]]

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

func Empty[E any]() Iterator[E]

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

func Enumerate[E any](iter Iterator[E]) Iterator[Pair[int, E]]

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

func FromBytesScanner(sc *bufio.Scanner) Iterator[[]byte]

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

func FromChan[E any](c <-chan E) Iterator[E]

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 FromCore

func FromCore[E any](core Core[E]) Iterator[E]

FromCore upgrades a Core type into a full Iterator.

func FromCoreFunc

func FromCoreFunc[E any](fn CoreFunc[E]) Iterator[E]

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

func FromGenerator[E any](gen *generator.Generator[E]) Iterator[E]

FromGenerator creates an Iterator from a generator.Generator.

func FromGeneratorFunc added in v0.1.1

func FromGeneratorFunc[E any](genFn func(yield func(E))) Iterator[E]

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 FromItems

func FromItems[E any](items ...E) Iterator[E]

FromItems creates an Iterator from the provided items.

func FromSlice

func FromSlice[E any](s []E) Iterator[E]

FromSlice returns an Iterator over the provided slice.

func FromStringScanner

func FromStringScanner(sc *bufio.Scanner) Iterator[string]

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

func Map[A, B any](iter Iterator[A], fn MapFunc[A, B]) Iterator[B]

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

func Scan[S, A, B any](iter Iterator[A], initial S, fn ScanFunc[S, A, B]) Iterator[B]

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

func Zip[E1, E2 any](a Iterator[E1], b Iterator[E2]) Iterator[Pair[E1, E2]]

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

func (iter Iterator[_]) AdvanceBy(n uint) (ct uint, ok bool)

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

func (iter Iterator[E]) All(pred Predicate[E]) bool

All returns true if all elements of the Iterator match the provided Predicate.

func (Iterator[E]) Any

func (iter Iterator[E]) Any(pred Predicate[E]) bool

Any returns true if at least one element of the Iterator matches the provided Predicate.

func (Iterator[E]) Chain

func (iter Iterator[E]) Chain(iters ...Iterator[E]) Iterator[E]

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

func (iter Iterator[_]) Count() (ct uint)

Count calls Iterator.Next repeatedly until the first time ok is false, returning the number of elements it saw.

func (Iterator[E]) Filter

func (iter Iterator[E]) Filter(pred Predicate[E]) Iterator[E]

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

func (iter Iterator[E]) Find(pred Predicate[E]) (match E, ok bool)

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

func (iter Iterator[E]) Fuse() Iterator[E]

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

func (iter Iterator[E]) Inspect(fn func(E)) Iterator[E]

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

func (iter Iterator[E]) Intersperse(sep E) Iterator[E]

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

func (iter Iterator[E]) IntersperseWith(sepFn func() E) Iterator[E]

IntersperseWith behaves the same as Iterator.Intersperse, but uses the provided function to generate the separator.

func (Iterator[E]) Last

func (iter Iterator[E]) Last() (last E, ok bool)

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

func (iter Iterator[E]) MaxBy(fn LessFunc[E]) (E, bool)

MaxBy consumes the provided Iterator, returning the maximum value determined by the specified LessFunc.

func (Iterator[E]) MinBy

func (iter Iterator[E]) MinBy(fn LessFunc[E]) (min E, ok bool)

MinBy consumes the Iterator, returning the minimum value determined by the specified LessFunc.

func (Iterator[E]) Next

func (iter Iterator[E]) Next() (next E, ok bool)

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

func (iter Iterator[E]) Nth(n uint) (nth E, ok bool)

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

func (iter Iterator[E]) Partition(pred Predicate[E]) (trues []E, falses []E)

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

func (iter Iterator[E]) Position(pred Predicate[E]) (idx uint, ok bool)

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

func (iter Iterator[E]) Skip(n uint) Iterator[E]

Skip returns a new Iterator that advances the current iterator by n before returning the Next element.

func (Iterator[E]) SkipWhile

func (iter Iterator[E]) SkipWhile(pred Predicate[E]) Iterator[E]

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

func (iter Iterator[E]) StepBy(n uint) Iterator[E]

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

func (iter Iterator[E]) Take(n uint) Iterator[E]

Take returns a new Iterator that limits the number of elements returned to the specified number.

func (Iterator[E]) TakeWhile

func (iter Iterator[E]) TakeWhile(pred Predicate[E]) Iterator[E]

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

func (iter Iterator[E]) TryForEach(fn func(E) error) error

TryForEach performs the same behavior as ForEach, but if the provided function returns an error, execution stops early and the error is returned.

func (Iterator[E]) TryReduce

func (iter Iterator[E]) TryReduce(fn TryReduceFunc[E]) (result E, ok bool, err error)

TryReduce is a specialization of TryFold that uses the first element of the Iterator as the initial accumulator value. The ok value is false if the iterator is empty.

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

type LessFunc[T any] func(a, b T) (aLessThanB bool)

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 Pair

type Pair[A, B any] struct {
	A A
	B B
}

Pair is a "tuple" of two values of any types.

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

type PeekIterator[E any] struct {
	Iterator[E]
	// contains filtered or unexported fields
}

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

type Predicate[T any] func(value T) (matches bool)

A Predicate function receives a value and returns true if the value matches the predicate and should be emitted.

type ReduceFunc

type ReduceFunc[T any] FoldFunc[T, T]

ReduceFunc is a FoldFunc that uses the same type for the state and element values.

type ScanFunc

type ScanFunc[S, A, B any] func(state *S, from A) (to B, ok bool)

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

type TryFoldFunc[S, T any] func(state S, value T) (S, error)

TryFoldFunc is a FoldFunc that may also return an error, short-circuiting accumulation.

type TryPredicate

type TryPredicate[T any] func(value T) (matches bool, err error)

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.

Directories

Path Synopsis
Package generator brings generator/coroutine support to Go
Package generator brings generator/coroutine support to Go

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL