seq

package
v0.0.0-...-16b3867 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2025 License: GPL-3.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Chunk

func Chunk[T any](sq iter.Seq[T], size int) iter.Seq[iter.Seq[T]]

Chunk returns an iterator over consecutive sub-slices of up to n elements of s. All but the last iter.Seq chunk will have size n. Chunk panics if n is less than 1.

func Chunk2

func Chunk2[K any, V any](sq iter.Seq2[K, V], size int) iter.Seq[iter.Seq2[K, V]]

Chunk2 returns an iterator over consecutive sub-slices of up to n elements of s. All but the last iter.Seq chunk will have size n. Chunk2 panics if n is less than 1.

func Collect2

func Collect2[K comparable, V any](it iter.Seq2[K, V]) map[K]V

Collect2 collects all key-value pairs from an iter.Seq2[K, V] into a map[K]V.

Example usage:

seq := seq.ToSeq2(seq.ToSeq(1, 2, 3), func(v int) string { return fmt.Sprintf("Key%d", v) })
result := seq.Collect2(seq)

fmt.Println(result) // Output: map[Key1:1 Key2:2 Key3:3]

func Count

func Count[T any](s iter.Seq[T]) int64

Count counts the number of elements in a sequence.

Parameters:

  • s: An input sequence of elements.

Returns:

  • The total count of elements in the sequence.

Example:

  seq := iter.Seq[int](func(yield func(int) bool) {
	   yield(1)
	   yield(2)
	   yield(3)
  })

  count := Count(seq)
  fmt.Println(count) // Output: 3

Notes:

  • The sequence `s` will be completely consumed by this function.

func Count2

func Count2[K any, V any](s iter.Seq2[K, V]) int64

Count2 counts the number of key-value pairs in a sequence of pairs.

Parameters:

  • s: An input sequence of key-value pairs.

Returns:

  • The total count of key-value pairs in the sequence.

Example:

  seq := iter.Seq2[int, string](func(yield func(int, string) bool) {
	   yield(1, "a")
	   yield(2, "b")
	   yield(3, "c")
  })

  count := Count2(seq)
  fmt.Println(count) // Output: 3

Notes:

  • The sequence `s` will be completely consumed by this function.

func Empty

func Empty[T any]() iter.Seq[T]

Empty returns an iter.Seq[T] that does not yield any items.

Example usage:

for i := range seq.Empty[int]() {
	fmt.Println(i) // This will not print anything as the sequence is empty
}

This can be useful when you need to provide an empty sequence to a function that expects an iter.Seq[T], without requiring any special case handling for the caller.

func Empty2

func Empty2[K comparable, V any]() iter.Seq2[K, V]

Empty2 returns an iter.Seq2[K, V] that does not yield any items.

Example usage:

for k, v := range seq.Empty2[int, string]() {
	fmt.Println(k, v) // This will not print anything as the sequence is empty
}

This can be useful when you need to provide an empty sequence to a function that expects an iter.Seq2[K, V], without requiring any special case handling for the caller.

func Filter

func Filter[T any](it iter.Seq[T], predicate func(i T) bool) iter.Seq[T]

Filter filters elements from an iter.Seq[T] that match the given predicate function.

Parameters:

  • it: The input sequence of type T.
  • predicate: A function that takes an element of type T and returns a boolean indicating whether the element should be included in the resulting sequence.

Returns:

  • An iter.Seq[T] containing only those elements of the input sequence that satisfy the predicate.

Example usage:

seq := seq.ToSeq(1, 2, 3, 4, 5)
filtered := seq.Filter(seq, func(i int) bool { return i%2 == 0 })

for v := range filtered {
	fmt.Println(v) // Output: 2, 4
}

func Filter2

func Filter2[K any, V any](it iter.Seq2[K, V], predicate func(k K, v V) bool) iter.Seq2[K, V]

Filter2 filters key-value pairs from an iter.Seq2[K, V] that satisfy the given predicate function.

Parameters:

  • it: The input sequence of key-value pairs.
  • predicate: A function that takes a key and a value, returning true if the pair should be included in the resulting sequence and false otherwise.

Returns:

  • An iter.Seq2[K, V] containing only those key-value pairs of the input sequence that satisfy the predicate.

Example usage:

pairs := seq.ToSeq2(seq.ToSeq(1, 2, 3), func(v int) string { return fmt.Sprintf("Key%d", v) })
filtered := seq.Filter2(pairs, func(k string, v int) bool { return v%2 == 1 })

for k, v := range filtered {
	fmt.Println(k, v) // Output: Key1 1, Key3 3
}

func FilterErrors

func FilterErrors[K any](s iter.Seq2[K, error]) iter.Seq[K]

FilterErrors takes an iter.Seq2[K, error] and returns an iter.Seq[K] containing only the elements whose associated error was nil.

Parameters:

  • s: A sequence of key-error pairs where K is the key type.

Returns:

  • An iter.Seq[K] that yields only the key values whose corresponding error was nil.

Example:

seq := iter.Seq2[string, error](func(yield func(string, error) bool) {
	yield("success", nil)              // This will be included
	yield("failure", errors.New(""))   // This will be filtered out
	yield("success2", nil)             // This will be included
	return true
})
filtered := FilterErrors(seq)
for k := range filtered {
	fmt.Println(k) // Prints: success, success2
}

func FilterNotError

func FilterNotError[K any](s iter.Seq2[K, error]) iter.Seq[K]

FilterNotError takes an iter.Seq2[K, error] and returns an iter.Seq[K] containing only the elements whose associated error was not nil.

Parameters:

  • s: A sequence of key-error pairs where K is the key type.

Returns:

  • An iter.Seq[K] that yields only the key values whose corresponding error was not nil.

Example:

seq := iter.Seq2[string, error](func(yield func(string, error) bool) {
	yield("success", nil)              // This will be filtered out
	yield("failure", errors.New(""))   // This will be included
	yield("success2", nil)             // This will be filtered out
	return true
})
filtered := FilterNotError(seq)
for k := range filtered {
	fmt.Println(k) // Prints: failure
}

func FindFirst

func FindFirst[T any](it iter.Seq[T], predicate func(i T) bool) iter.Seq[T]

First returns the first item in the sequence that matches the predicate. if no item matches the predicate then the sequence is empty.

func First

func First[T any](it iter.Seq[T]) (T, bool)

First returns the first item in the sequence. If the sequence is empty, it returns nil, false.

func FirstN

func FirstN[T any](it iter.Seq[T], limit int) iter.Seq[T]

FirstN takes an iter.Seq[int] and returns a new iter.Seq[int] that yields only the first 'limit' or less items without creating intermediate slices. if there are less than limit items in the sequence then the sequence ends when the sequence end is reached.

func FlattenSeq

func FlattenSeq[T any](iterSeqs ...iter.Seq[T]) iter.Seq[T]

FlattenSeq takes an iter.Seq of batches (iter.Seq[T]) and flat maps all the batches into a single iter.Seq.

func IntRange

func IntRange[N Integer](start N, end N) iter.Seq[N]

IntRange returns an iter.Seq that yields a sequence of integers from start to end inclusive.

for i := range IntRange(1, 5) {
	fmt.Println(i) // 1, 2, 3, 4, 5
}

func JsonMarshalCompact

func JsonMarshalCompact[T any](w io.Writer, seq iter.Seq[T]) error

JsonMarshalCompact serializes the given sequence into a compact JSON array and writes it to the provided writer.

Parameters:

  • w: An `io.Writer` where the serialized JSON array is written.
  • seq: A sequence `iter.Seq[T]` of elements to be serialized.

Returns:

  • An error if any issue occurs during marshaling or writing.

Notes:

  • Uses a buffered writer for efficient writing, ensuring any pending data is flushed at the end.
  • Serializes the sequence items one by one, maintaining a compact JSON format without extra whitespace.

Example:

seq := iter.Seq[int](func(yield func(int) bool) {
    yield(1)
    yield(2)
    yield(3)
})

var buf bytes.Buffer
err := JsonMarshalCompact(&buf, seq)
if err != nil {
    log.Fatal(err)
}
fmt.Println(buf.String()) // Output: [1,2,3]

If the writer fails at any point, marshaling stops and an error is returned.

func Keys

func Keys[K any, V any](s iter.Seq2[K, V]) iter.Seq[K]

func Map

func Map[T any, R any](it iter.Seq[T], mapFunc func(t T) R) iter.Seq[R]

Map also known as transform function, list comprehension, visitor pattern whatever. this takes an iter.Seq and a function to apply to each item in the sequence returning a new iter.Seq with the results.

func Map2

func Map2[K any, V any, KR any, VR any](it iter.Seq2[K, V], keyFunc func(k K) KR, valFunc func(v V) VR) iter.Seq2[KR, VR]

Map2 this does the same but allows you to transform the key and/or the value.

func Min

func Min[T cmp.Ordered](it iter.Seq[T]) T

Min returns the minimum value in the sequence. It uses the cmp.Ordered constraint to compare values. It assumes the sequence is not empty. If the sequence is empty it will panic.

func PassThruFunc

func PassThruFunc[K any](k K) K

PassThruFunc passes thru the value unchanged this is just a convenience function for times when you do not want to transform the key or value in Map2 so you do not have to write an inline function and clutter up the code more than it needs to be.

func Reduce

func Reduce[T any, A any](s iter.Seq[T], initialValue A, f func(A, T) A) A

Reduce reduces a sequence to a single value by repeatedly applying a function to an accumulator and each element of the sequence.

Parameters:

  • s: An input sequence of elements.
  • initialValue: The initial value of the accumulator.
  • f: A function that combines the accumulator with an element from the sequence.

Returns:

  • The final accumulated value after processing the entire sequence.

Example:

  seq := iter.Seq[int](func(yield func(int) bool) {
	   yield(1)
	   yield(2)
	   yield(3)
  })

  sum := Reduce(seq, 0, func(acc, val int) int {
	   return acc + val
  })
  fmt.Println(sum) // Output: 6

Notes:

  • The sequence `s` will be consumed entirely by this function.
  • The function `f` must be capable of reducing any two elements into the accumulator.

func Reduce2

func Reduce2[K any, V any, A any](s iter.Seq2[K, V], initialValue A, f func(A, K, V) A) A

Reduce2 reduces a sequence of key-value pairs to a single value by repeatedly applying a function to an accumulator and each key-value pair from the sequence.

Parameters:

  • s: An input sequence of key-value pairs.
  • initialValue: The initial value of the accumulator.
  • f: A function that combines the accumulator with a key and a value from the sequence.

Returns:

  • The final accumulated value after processing the entire sequence.

Example:

  seq := iter.Seq2[int, string](func(yield func(int, string) bool) {
	   yield(1, "a")
	   yield(2, "b")
	   yield(3, "c")
  })

  result := Reduce2(seq, "", func(acc string, k int, v string) string {
	   return acc + fmt.Sprintf("%d:%s ", k, v)
  })
  fmt.Println(result) // Output: "1:a 2:b 3:c "

Notes:

  • The sequence `s` will be consumed entirely by this function.
  • The function `f` must be capable of reducing the key-value pairs into the accumulator.

func RuneSeq

func RuneSeq(s string) iter.Seq[rune]

RuneSeq creates a sequence of runes from the given string.

The sequence iterates over all runes in the input string and passes each rune to the provided yielding function until all runes are processed, or the yielding function returns false to stop the iteration.

Parameters:

  • s: The input string to generate the rune sequence from.

Returns:

  • iter.Seq[rune]: A sequence that yields runes from the input string.

Example:

  seq := RuneSeq("hello")
  seq(func(r rune) bool {
	   fmt.Printf("Rune: %c\n", r)
	   return true // Continue iteration
  })

func RuneSeq2

func RuneSeq2(s string) iter.Seq2[int, rune]

RuneSeq2 creates a sequence of runes from the given string, where each yielded element is a key-value pair consisting of the index and the rune at that index in the string.

The sequence will iterate over the string, yielding the index and corresponding rune until all runes in the string have been processed, or until the yielding function returns false to stop iteration.

Parameters:

  • s: The input string to generate the rune sequence from.

Returns:

  • iter.Seq2[int,rune]: A sequence that yields index-rune pairs from the string.

Example:

  seq := RuneSeq2("hello")
  seq(func(idx int, r rune) bool {
	   fmt.Printf("Index: %d, Rune: %c\n", idx, r)
	   return true // Continue iteration
  })

func Seq2ToMap

func Seq2ToMap[K comparable, V any](seq iter.Seq2[K, V]) map[K]V

Seq2ToMap converts an iter.Seq2[string, any] to a map[string]any.

Parameters:

  • seq: An input sequence of key-value pairs.

Returns:

  • A map[string]any containing the key-value pairs from the input sequence.

this just delegates to maps.Collect() because I keep forgetting it exists Deprecated: Use maps.Collect instead for more streamlined functionality.

func SkipAndLimit

func SkipAndLimit[V any](it iter.Seq[V], skip int, limit int) iter.Seq[V]

SkipAndLimit combines SkipFirstN and FirstN in a way that allows accessing sub sequences without any overhead. it first SkipFirstN items using skip and then returns the next FirstN or less items in limit. using this instead of inlining it shows more intent because of the semantic of the name. if skip is greater than the number of items in the sequence then an empty sequence is returned. if limit is greater than the number of items remaining in the sequence then the sequence will contain less than limit number of items in it.

func SkipFirstN

func SkipFirstN[T any](seq iter.Seq[T], skip int) iter.Seq[T]

SkipFirstN skips the first N items in the sequence and then iterates over the rest of them normally. if skip is greater than the number of items in the sequence then an empty sequence is returned.

func Sum

func Sum[T Number](s iter.Seq[T]) T

Sum calculates the sum of a sequence of numbers.

Parameters:

  • s: An input sequence of numeric elements.

Returns:

  • The sum of all elements in the sequence.

Example:

  seq := iter.Seq[int](func(yield func(int) bool) {
	   yield(1)
	   yield(2)
	   yield(3)
  })

  total := Sum(seq)
  fmt.Println(total) // Output: 6

func ToSeq

func ToSeq[T any](seq ...T) iter.Seq[T]

ToSeq takes a slice of type T and returns an iter.Seq[T] that yields each item in the slice.

for i := range ToSeq([]int{1, 2, 3}) {
	fmt.Println(i) // 1, 2, 3
}

func ToSeq2

func ToSeq2[K any, V any](is iter.Seq[V], keyFunc func(v V) K) iter.Seq2[K, V]

ToSeq2 converts an iter.Seq[V] to an iter.Seq2[K, V] by applying a key function to each value. This is useful when you have a sequence of values and you want to associate a key with each value. The key function is applied to each value in the sequence to generate the key. The original value is preserved as the value in the resulting iter.Seq2.

func Unique

func Unique[T any](s iter.Seq[T]) iter.Seq[T]

Unique filters a sequence to include only unique elements based on their hash identity.

It ensures that only one instance of each unique element is yielded, with uniqueness determined by a hash of the element.

Parameters:

  • s: An input sequence of elements.

Returns:

  • A new sequence containing only unique elements from the input sequence.

Notes:

  • The uniqueness of elements is determined using their hash identity via MustHashIdentity.
  • If elements cannot be hashed correctly, this function might panic.

Example:

  seq := iter.Seq[int](func(yield func(int) bool) {
		 yield(1)
		 yield(2)
		 yield(2)
		 yield(3)
  })

  uniqueSeq := Unique(seq)
  for v := range uniqueSeq {
	   fmt.Println(v) // Output: 1, 2, 3
  }

func UnzipMap

func UnzipMap[K comparable, V any](m map[K]V) ([]K, []V)

UnzipMap splits a map into two slices: one containing its keys and the other its values.

Parameters:

  • m: The input map of type map[K]V.

Returns:

  • A slice of keys ([]K) and a slice of values ([]V) extracted from the input map, sorted by the keys to ensure consistency in ordering.

Example:

  m := map[string]int{
	   "a": 1,
	   "b": 2,
	   "c": 3,
  }

  keys, values := UnzipMap(m)
  fmt.Println(keys)   // Output: [a b c]
  fmt.Println(values) // Output: [1 2 3]

func Values

func Values[K any, V any](s iter.Seq2[K, V]) iter.Seq[V]

Types

type CountingSeq

type CountingSeq[T any] struct {
	Seq iter.Seq[T]
	// contains filtered or unexported fields
}

CountingSeq is a wraps an iter.Seq and counts the number of elements that have been iterated over.

func WrapWithCounter

func WrapWithCounter[T any](it iter.Seq[T]) *CountingSeq[T]

WrapWithCounter takes an iter.Seq and returns a *CountingSeq. The *CountingSeq will count the number of items that have been yielded when the Seq function is called. This is useful for debugging and testing.

func (CountingSeq[T]) Count

func (c CountingSeq[T]) Count() int64

type Decimal

type Decimal interface {
	float32 | float64
}

type Integer

type Integer interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}

type MemoizeSeq

type MemoizeSeq[T any] struct {
	// contains filtered or unexported fields
}

func Memoize

func Memoize[T any](s iter.Seq[T]) *MemoizeSeq[T]

func (*MemoizeSeq[T]) Len

func (m *MemoizeSeq[T]) Len() int

func (*MemoizeSeq[T]) Seq

func (m *MemoizeSeq[T]) Seq() iter.Seq[T]

func (*MemoizeSeq[T]) Seq2

func (m *MemoizeSeq[T]) Seq2() iter.Seq2[int, T]

type Number

type Number interface {
	Integer | Decimal
}

Number is a union of Integer and Decimal.

Jump to

Keyboard shortcuts

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