iter

package module
v0.0.0-...-f158332 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2025 License: MIT Imports: 4 Imported by: 1

README

GOPHER_ROCKS

iter — Lazy Iterators with Generics for Go

Go Reference Go Report Card Coverage Status Go Ask DeepWiki

iter is a library of lazy iterators for Go. Built on pure functions, no unnecessary allocations, with full generics support and a clean functional style.

Apply transformations like Map, Filter, Take, Fold, Zip directly to sequences — lazily and efficiently.


📦 Installation

go get github.com/enetx/iter

🚀 Example

package main

import (
	"fmt"
	"github.com/enetx/iter"
)

func main() {
	// Extract even numbers and square them:
	s := iter.FromSlice([]int{1, 2, 3, 4, 5})
	s = iter.Filter(s, func(x int) bool { return x%2 == 0 })        // 2, 4
	s = iter.Map(s, func(x int) int { return x * x })              // 4, 16
	out := iter.ToSlice(s)
	fmt.Println(out) // [4 16]
}

✨ Features

  • Lazy sequences — transformations are not applied until iteration begins.
  • Generics-powered — works with any types T, U, structs, etc.
  • Zero-allocation — avoids unnecessary memory allocations.
  • Functional API — each transformation is a pure function: Map, Filter, Take, Skip, StepBy, Flatten, Zip, Enumerate, Fold, Reduce, and many more.
  • Supports pairs, maps, channelsSeq2, FromMap, FromChan, and beyond.

🔬 More Examples

// Simple range with step
r := iter.Iota(1, 10) // 1..9
r = iter.StepBy(r, 3)  // 1, 4, 7
fmt.Println(iter.ToSlice(r)) // → [1 4 7]

// Iterate over a map
m := map[string]int{"a": 1, "b": 2}
s2 := iter.FromMap(m)
iter.ForEach2(s2, func(k string, v int) {
	fmt.Printf("%s → %d\n", k, v)
})

⚖️ License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func All

func All[T any](s Seq[T], p func(T) bool) bool

All returns true if all elements satisfy the predicate.

Example:

s := iter.FromSlice([]int{2, 4, 6, 8})
allEven := iter.All(s, func(x int) bool { return x%2 == 0 }) // true

func All2

func All2[K, V any](s Seq2[K, V], p func(K, V) bool) bool

All2 returns true if all key-value pairs satisfy the predicate.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b"})
allShortValues := iter.All2(s, func(k int, v string) bool { return len(v) == 1 }) // true

func Any

func Any[T any](s Seq[T], p func(T) bool) bool

Any returns true if any element satisfies the predicate.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
hasEven := iter.Any(s, func(x int) bool { return x%2 == 0 }) // true

func Any2

func Any2[K, V any](s Seq2[K, V], p func(K, V) bool) bool

Any2 returns true if any key-value pair satisfies the predicate.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "bb"})
hasLongValue := iter.Any2(s, func(k int, v string) bool { return len(v) > 1 }) // true

func Cmp

func Cmp[T any](a, b Seq[T], cmp func(T, T) int) int

Cmp compares two sequences lexicographically using the provided comparison function. Returns -1 if a < b, 0 if a == b, 1 if a > b.

Example:

s1 := iter.FromSlice([]int{1, 2, 3})
s2 := iter.FromSlice([]int{1, 2, 4})
result := iter.Cmp(s1, s2, func(a, b int) int {
  if a < b { return -1 }
  if a > b { return 1 }
  return 0
}) // -1

func Contains

func Contains[T comparable](s Seq[T], x T) bool

Contains checks if the sequence contains the given value.

Example:

s := iter.FromSlice([]int{1, 2, 3})
has := iter.Contains(s, 2) // true

func Count

func Count[T any](s Seq[T]) int

Count returns the number of elements in the sequence.

Example:

s := iter.FromSlice([]int{1, 2, 3})
count := iter.Count(s) // 3

func Count2

func Count2[K, V any](s Seq2[K, V]) int

Count2 returns the number of key-value pairs in the sequence.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b"})
count := iter.Count2(s) // 2

func CountBy

func CountBy[T any, K comparable](s Seq[T], key func(T) K) map[K]int

CountBy counts elements by grouping them using a key function.

Example:

s := iter.FromSlice([]string{"a", "bb", "ccc", "dd"})
counts := iter.CountBy(s, func(s string) int { return len(s) })
// map[1:1 2:2 3:1]

func Counter

func Counter[T any](s Seq[T]) map[any]int

Counter returns a map with counts of each element.

Example:

s := iter.FromSlice([]int{1, 2, 1, 3, 2, 1})
counts := iter.Counter(s) // map[1:3 2:2 3:1]

func Equal

func Equal[T any](a, b Seq[T]) bool

Equal checks if two sequences are equal (same elements in same order).

Example:

s1 := iter.FromSlice([]int{1, 2, 3})
s2 := iter.FromSlice([]int{1, 2, 3})
equal := iter.Equal(s1, s2) // true

func EqualBy

func EqualBy[T any](a, b Seq[T], eq func(T, T) bool) bool

func Find

func Find[T any](s Seq[T], p func(T) bool) (T, bool)

Find returns the first element that satisfies the predicate.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
value, ok := iter.Find(s, func(x int) bool { return x > 3 }) // 4, true

func Find2

func Find2[K, V any](s Seq2[K, V], p func(K, V) bool) (K, V, bool)

Find2 returns the first key-value pair that satisfies the predicate.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "bb", 3: "ccc"})
k, v, ok := iter.Find2(s, func(k int, v string) bool { return len(v) > 1 })
// might return: 2, "bb", true

func First

func First[T any](s Seq[T]) (T, bool)

First returns the first element from the sequence. Returns (value, true) if an element exists, or (zero, false) if empty. This is similar to Rust's Iterator::first() method.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
value, ok := iter.First(s) // 1, true

func First2

func First2[K, V any](s Seq2[K, V]) (K, V, bool)

First2 returns the first key-value pair from the sequence. Returns (key, value, true) if a pair exists, or (zeroK, zeroV, false) if empty. This is similar to Rust's Iterator::first() method for key-value pairs.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b", 3: "c"})
k, v, ok := iter.First2(s) // might return: 1, "a", true

func Fold

func Fold[T, A any](s Seq[T], acc A, f func(A, T) A) A

Fold reduces the sequence to a single value using an accumulator.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4})
sum := iter.Fold(s, 0, func(acc, x int) int { return acc + x }) // 10

func Fold2

func Fold2[K, V, A any](s Seq2[K, V], acc A, f func(A, K, V) A) A

Fold2 reduces the Seq2 to a single value using an accumulator.

Example:

s := iter.FromMap(map[int]int{1: 10, 2: 20, 3: 30})
sum := iter.Fold2(s, 0, func(acc, k, v int) int { return acc + k + v }) // 66

func ForEach

func ForEach[T any](s Seq[T], fn func(T))

ForEach applies a function to each element in the sequence.

Example:

s := iter.FromSlice([]int{1, 2, 3})
iter.ForEach(s, func(x int) { fmt.Println(x) })

func ForEach2

func ForEach2[K, V any](s Seq2[K, V], fn func(K, V))

ForEach2 applies a function to each key-value pair in the sequence.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b"})
iter.ForEach2(s, func(k int, v string) { fmt.Printf("%d: %s\n", k, v) })

func Ge

func Ge[T any](a, b Seq[T], less func(T, T) bool) bool

Ge checks if sequence a is lexicographically greater than or equal to sequence b.

Example:

s1 := iter.FromSlice([]int{1, 2, 3})
s2 := iter.FromSlice([]int{1, 2, 3})
isGreaterOrEqual := iter.Ge(s1, s2, func(a, b int) bool { return a < b }) // true

func Gt

func Gt[T any](a, b Seq[T], less func(T, T) bool) bool

Gt checks if sequence a is lexicographically greater than sequence b.

Example:

s1 := iter.FromSlice([]int{1, 2, 4})
s2 := iter.FromSlice([]int{1, 2, 3})
isGreater := iter.Gt(s1, s2, func(a, b int) bool { return a < b }) // true

func IsPartitioned

func IsPartitioned[T any](s Seq[T], pred func(T) bool) bool

IsPartitioned checks if the sequence is partitioned according to the predicate. A sequence is partitioned if all elements satisfying the predicate come before all elements that don't.

Example:

s := iter.FromSlice([]int{2, 4, 6, 1, 3, 5})
partitioned := iter.IsPartitioned(s, func(x int) bool { return x%2 == 0 }) // true

func Last

func Last[T any](s Seq[T]) (T, bool)

Last returns the last element from the sequence. Returns (value, true) if an element exists, or (zero, false) if empty. This is similar to Rust's Iterator::last() method.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
value, ok := iter.Last(s) // 5, true

func Last2

func Last2[K, V any](s Seq2[K, V]) (K, V, bool)

Last2 returns the last key-value pair from the sequence. Returns (key, value, true) if a pair exists, or (zeroK, zeroV, false) if empty. This is similar to Rust's Iterator::last() method for key-value pairs.

Example:

pairs := []Pair[int, string]{{1, "a"}, {2, "b"}, {3, "c"}}
s := iter.FromPairs(pairs)
k, v, ok := iter.Last2(s) // 3, "c", true

func Le

func Le[T any](a, b Seq[T], less func(T, T) bool) bool

Le checks if sequence a is lexicographically less than or equal to sequence b.

Example:

s1 := iter.FromSlice([]int{1, 2, 3})
s2 := iter.FromSlice([]int{1, 2, 3})
isLessOrEqual := iter.Le(s1, s2, func(a, b int) bool { return a < b }) // true

func Lt

func Lt[T any](a, b Seq[T], less func(T, T) bool) bool

Lt checks if sequence a is lexicographically less than sequence b.

Example:

s1 := iter.FromSlice([]int{1, 2, 3})
s2 := iter.FromSlice([]int{1, 2, 4})
isLess := iter.Lt(s1, s2, func(a, b int) bool { return a < b }) // true

func MaxBy

func MaxBy[T any](s Seq[T], less func(a, b T) bool) (T, bool)

MaxBy returns the maximum element according to the comparison function.

Example:

s := iter.FromSlice([]int{3, 1, 4, 1, 5})
max, ok := iter.MaxBy(s, func(a, b int) bool { return a < b }) // 5, true

func MinBy

func MinBy[T any](s Seq[T], less func(a, b T) bool) (T, bool)

MinBy returns the minimum element according to the comparison function.

Example:

s := iter.FromSlice([]int{3, 1, 4, 1, 5})
min, ok := iter.MinBy(s, func(a, b int) bool { return a < b }) // 1, true

func Nth

func Nth[T any](s Seq[T], n int) (T, bool)

Nth returns the nth element (0-indexed) from the sequence.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
value, ok := iter.Nth(s, 2) // 3, true

func Nth2

func Nth2[K, V any](s Seq2[K, V], n int) (K, V, bool)

Nth2 returns the nth key-value pair (0-indexed) from the sequence.

Example:

pairs := []Pair[int, string]{{1, "a"}, {2, "b"}, {3, "c"}}
s := iter.FromPairs(pairs)
k, v, ok := iter.Nth2(s, 1) // 2, "b", true

func Partition

func Partition[T any](s Seq[T], pred func(T) bool) (left, right []T)

Partition splits the sequence into two slices based on a predicate.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
evens, odds := iter.Partition(s, func(x int) bool { return x%2 == 0 })
// evens: [2, 4], odds: [1, 3, 5]

func Position

func Position[T any](s Seq[T], pred func(T) bool) (int, bool)

Position returns the index of the first element that satisfies the predicate.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
pos, ok := iter.Position(s, func(x int) bool { return x > 3 }) // 3, true

func Pull

func Pull[T any](s Seq[T]) (next func() (T, bool), stop func())

Pull converts a push-style iterator (Seq) to a pull-style iterator. Returns a next function that yields the next value and a boolean indicating if valid, and a stop function that should be called to release resources.

Example:

next, stop := iter.Pull(iter.FromSlice([]int{1, 2, 3}))
defer stop()
for {
  v, ok := next()
  if !ok { break }
  fmt.Println(v)
}

func Pull2

func Pull2[K, V any](s Seq2[K, V]) (next func() (K, V, bool), stop func())

Pull2 converts a push-style iterator (Seq2) to a pull-style iterator.

func RPosition

func RPosition[T any](s Seq[T], pred func(T) bool) (int, bool)

RPosition returns the index of the last element that satisfies the predicate.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 3, 2})
pos, ok := iter.RPosition(s, func(x int) bool { return x == 3 }) // 4, true

func Range

func Range[T any](s Seq[T], fn func(T) bool)

Range applies a function to each element until it returns false. This is the same as the sequence's yield function.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
iter.Range(s, func(x int) bool {
  fmt.Println(x)
  return x != 3 // Stop at 3
})

func Range2

func Range2[K, V any](s Seq2[K, V], fn func(K, V) bool)

Range2 applies a function to each key-value pair until it returns false.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b", 3: "c"})
iter.Range2(s, func(k int, v string) bool {
  fmt.Printf("%d: %s\n", k, v)
  return k != 2 // Stop at key 2
})

func Reduce

func Reduce[T any](s Seq[T], f func(T, T) T) (T, bool)

Reduce reduces the sequence to a single value of the same type. Returns false if the sequence is empty.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4})
sum, ok := iter.Reduce(s, func(a, b int) int { return a + b }) // 10, true

func ToChan

func ToChan[T any](s Seq[T], ctx context.Context) chan T

ToChan converts a sequence to a channel. The channel is closed when the sequence is exhausted or context is cancelled.

Example:

ctx := context.Background()
ch := iter.ToChan(iter.FromSlice([]int{1, 2, 3}), ctx)
for v := range ch {
  fmt.Println(v)
}

func ToChan2

func ToChan2[K, V any](s Seq2[K, V], ctx context.Context) chan Pair[K, V]

ToChan2 converts a key-value sequence to a channel of Pair pairs. The channel is closed when the sequence is exhausted or context is cancelled.

Example:

ctx := context.Background()
ch := iter.ToChan2(iter.FromMap(map[int]string{1: "a", 2: "b"}), ctx)
for kv := range ch {
  fmt.Printf("%d: %s\n", kv.K, kv.V)
}

func ToMap

func ToMap[K comparable, V any](s Seq2[K, V]) map[K]V

ToMap collects all key-value pairs into a map. Later pairs with the same key will overwrite earlier ones.

func ToSlice

func ToSlice[T any](s Seq[T]) []T

ToSlice collects all elements from the sequence into a slice.

Example:

s := iter.FromSlice([]int{1, 2, 3})
sl := iter.ToSlice(s) // [1, 2, 3]

Types

type Integer

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

Integer defines numeric types that can be used with Iota generators. Supports all signed and unsigned integer types.

type Pair

type Pair[K, V any] struct {
	Key   K
	Value V
}

Pair represents a key-value pair. Used for converting between Seq2 and slice representations.

func Reduce2

func Reduce2[K, V any](s Seq2[K, V], f func(Pair[K, V], Pair[K, V]) Pair[K, V]) (Pair[K, V], bool)

Reduce2 reduces the Seq2 to a single Pair pair. Returns false if the sequence is empty.

Example:

s := iter.FromMap(map[int]int{1: 10, 2: 20})
result, ok := iter.Reduce2(s, func(a, b Pair[int, int]) Pair[int, int] {
  return Pair[int, int]{a.Key + b.Key, a.Value + b.Value}
}) // Pair{3, 30}, true

func ToPairs

func ToPairs[K, V any](s Seq2[K, V]) []Pair[K, V]

ToPairs collects all key-value pairs into a slice of Pair structs.

type Seq

type Seq[T any] iter.Seq[T]

Seq represents a single-value iterator sequence. It calls the yield function for each element in the sequence. If yield returns false, the iteration should stop.

func Chain

func Chain[T any](head Seq[T], rest ...Seq[T]) Seq[T]

Chain concatenates multiple sequences into one.

Example:

s1 := iter.FromSlice([]int{1, 2})
s2 := iter.FromSlice([]int{3, 4})
iter.Chain(s1, s2) // yields: 1, 2, 3, 4

func Chunks

func Chunks[T any](s Seq[T], n int) Seq[[]T]

Chunks returns a sequence of chunks of size n.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
iter.Chunks(s, 2) // yields: [1,2], [3,4], [5]

func Combinations

func Combinations[T any](s Seq[T], k int) Seq[[]T]

Combinations generates all combinations of k elements from the sequence.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4})
iter.Combinations(s, 2) // yields: [1,2], [1,3], [1,4], [2,3], [2,4], [3,4]

func Context

func Context[T any](s Seq[T], ctx context.Context) Seq[T]

Context wraps a sequence with context cancellation. If the context is cancelled, iteration stops early.

Example:

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
s := iter.Context(iter.FromSlice([]int{1, 2, 3}), ctx)

func Cycle

func Cycle[T any](s Seq[T]) Seq[T]

Cycle creates an infinite sequence by repeating the given sequence.

Example:

s := iter.FromSlice([]int{1, 2, 3})
iter.Take(iter.Cycle(s), 7) // yields: 1, 2, 3, 1, 2, 3, 1

func Dedup

func Dedup[T comparable](s Seq[T]) Seq[T]

Dedup removes consecutive duplicate elements.

Example:

s := iter.FromSlice([]int{1, 1, 2, 2, 2, 3, 3})
iter.Dedup(s) // yields: 1, 2, 3

func DedupBy

func DedupBy[T any](s Seq[T], eq func(a, b T) bool) Seq[T]

DedupBy removes consecutive elements where the provided function returns the same value.

Example:

s := iter.FromSlice([]string{"a", "aa", "b", "bb", "cc"})
iter.DedupBy(s, func(a, b string) bool { return len(a) == len(b) })
// yields: "a", "b", "cc"

func Empty

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

Empty creates an empty sequence.

Example:

s := iter.Empty[int]() // yields nothing

func Exclude

func Exclude[T any](s Seq[T], p func(T) bool) Seq[T]

Exclude returns a new sequence containing only elements that do not satisfy the predicate.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
iter.Exclude(s, func(x int) bool { return x%2 == 0 }) // yields: 1, 3, 5

func Filter

func Filter[T any](s Seq[T], p func(T) bool) Seq[T]

Filter returns a new sequence containing only elements that satisfy the predicate.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
iter.Filter(s, func(x int) bool { return x%2 == 0 }) // yields: 2, 4

func FilterMap

func FilterMap[T, U any](s Seq[T], f func(T) (U, bool)) Seq[U]

FilterMap applies a function to each element and filters out None results.

Example:

s := iter.FromSlice([]string{"1", "2", "abc", "3"})
iter.FilterMap(s, func(s string) (int, bool) {
  if i, err := strconv.Atoi(s); err == nil {
    return i, true
  }
  return 0, false
}) // yields: 1, 2, 3

func Flatten

func Flatten[T any](ss Seq[[]T]) Seq[T]

Flatten flattens a sequence of slices into a single sequence.

Example:

s := iter.FromSlice([][]int{{1, 2}, {3, 4}, {5}})
iter.Flatten(s) // yields: 1, 2, 3, 4, 5

func FlattenSeq

func FlattenSeq[T any](ss Seq[Seq[T]]) Seq[T]

FlattenSeq flattens a sequence of sequences into a single sequence.

Example:

seqs := []iter.Seq[int]{
  iter.FromSlice([]int{1, 2}),
  iter.FromSlice([]int{3, 4}),
}
s := iter.FromSlice(seqs)
iter.FlattenSeq(s) // yields: 1, 2, 3, 4

func FromChan

func FromChan[T any](ch <-chan T) Seq[T]

FromChan creates a sequence from a channel. The sequence will stop when the channel is closed.

Example:

ch := make(chan int)
go func() {
  defer close(ch)
  for i := 0; i < 3; i++ { ch <- i }
}()
s := iter.FromChan(ch)

func FromSlice

func FromSlice[T any](sl []T) Seq[T]

FromSlice creates a sequence that iterates over the given slice in forward order.

Example:

s := iter.FromSlice([]int{1, 2, 3})
iter.ForEach(s, func(x int) { fmt.Println(x) })
// Output:
// 1
// 2
// 3

func FromSliceReverse

func FromSliceReverse[T any](sl []T) Seq[T]

FromSliceReverse creates a sequence that iterates over the given slice in reverse order. Note: This does NOT allocate or collect; it walks the provided slice backwards.

Example:

s := iter.FromSliceReverse([]int{1, 2, 3})
iter.ForEach(s, func(x int) { fmt.Println(x) })
// Output:
// 3
// 2
// 1

func GroupByAdjacent

func GroupByAdjacent[T any](s Seq[T], same func(a, b T) bool) Seq[[]T]

GroupByAdjacent groups consecutive elements that are considered the same by the comparison function.

Example:

s := iter.FromSlice([]int{1, 1, 2, 2, 2, 3})
iter.GroupByAdjacent(s, func(a, b int) bool { return a == b })
// yields: [1,1], [2,2,2], [3]

func Inspect

func Inspect[T any](s Seq[T], fn func(T)) Seq[T]

Inspect applies a function to each element for side effects while passing through the original values.

Example:

s := iter.FromSlice([]int{1, 2, 3})
iter.Inspect(s, func(x int) { fmt.Printf("Processing: %d\n", x) })

func Interleave

func Interleave[T any](a, b Seq[T]) Seq[T]

Interleave alternates between elements from two sequences.

Example:

s1 := iter.FromSlice([]int{1, 2, 3})
s2 := iter.FromSlice([]int{10, 20, 30})
iter.Interleave(s1, s2) // yields: 1, 10, 2, 20, 3, 30

func Intersperse

func Intersperse[T any](s Seq[T], sep T) Seq[T]

Intersperse inserts a separator between each element.

Example:

s := iter.FromSlice([]int{1, 2, 3})
iter.Intersperse(s, 0) // yields: 1, 0, 2, 0, 3

func Iota

func Iota[T Integer](start, stop T, step ...T) Seq[T]

Iota generates a sequence of numbers from start (inclusive) to stop (exclusive) with the given step. If no step is provided, defaults to 1.

Example:

iter.Iota(1, 5)    // yields: 1, 2, 3, 4
iter.Iota(1, 10, 2) // yields: 1, 3, 5, 7, 9

func IotaInclusive

func IotaInclusive[T Integer](start, stop T, step ...T) Seq[T]

IotaInclusive generates a sequence of numbers from start to stop (both inclusive) with the given step. If no step is provided, defaults to 1.

Example:

iter.IotaInclusive(1, 5)    // yields: 1, 2, 3, 4, 5
iter.IotaInclusive(1, 9, 2) // yields: 1, 3, 5, 7, 9

func Keys

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

Keys extracts all keys from the Seq2 into a Seq.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b"})
iter.Keys(s) // yields: 1, 2 (order not guaranteed)

func Map

func Map[T any](s Seq[T], f func(T) T) Seq[T]

Map applies a function to each element, producing a new sequence of the same type.

Example:

s := iter.FromSlice([]int{1, 2, 3})
iter.Map(s, func(x int) int { return x * 2 }) // yields: 2, 4, 6

func MapTo

func MapTo[T, U any](s Seq[T], f func(T) U) Seq[U]

MapTo applies a function to each element, producing a new sequence of potentially different type.

Example:

s := iter.FromSlice([]int{1, 2, 3})
iter.MapTo(s, func(x int) string { return fmt.Sprintf("%d", x) }) // yields: "1", "2", "3"

func MapWhile

func MapWhile[T, U any](s Seq[T], f func(T) (U, bool)) Seq[U]

MapWhile applies a function to elements while it returns Some, stopping at the first None.

Example:

s := iter.FromSlice([]int{1, 2, -1, 4})
iter.MapWhile(s, func(x int) (int, bool) {
  if x > 0 { return x * 2, true }
  return 0, false
}) // yields: 2, 4

func Next

func Next[T any](s Seq[T]) (T, Seq[T], bool)

Next extracts the first element from the sequence and returns the remaining sequence. Returns (value, remainingSeq, true) if an element exists, or (zero, nil, false) if empty. This is similar to Rust's Iterator::next() method.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
val, rest, ok := iter.Next(s)
// val = 1, ok = true
// rest yields: 2, 3, 4, 5

val2, rest2, ok2 := iter.Next(rest)
// val2 = 2, ok2 = true
// rest2 yields: 3, 4, 5

func Once

func Once[T any](value T) Seq[T]

Once creates a sequence that yields a single value.

Example:

s := iter.Once(42) // yields: 42

func OnceWith

func OnceWith[T any](f func() T) Seq[T]

OnceWith creates a sequence that yields a single value from a function.

Example:

s := iter.OnceWith(func() int { return rand.Int() })

func Permutations

func Permutations[T any](s Seq[T]) Seq[[]T]

Permutations generates all permutations of the sequence elements.

Example:

s := iter.FromSlice([]int{1, 2, 3})
iter.Permutations(s) // yields: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]

func Repeat

func Repeat[T any](value T) Seq[T]

Repeat creates an infinite sequence that repeats the given value.

Example:

s := iter.Take(iter.Repeat(42), 3) // yields: 42, 42, 42

func RepeatWith

func RepeatWith[T any](f func() T) Seq[T]

RepeatWith creates an infinite sequence by repeatedly calling a function.

Example:

s := iter.Take(iter.RepeatWith(func() int { return rand.Int() }), 3)

func Scan

func Scan[T, S any](s Seq[T], init S, f func(S, T) S) Seq[S]

Scan is similar to Fold, but emits intermediate accumulator values.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4})
iter.Scan(s, 0, func(acc, x int) int { return acc + x }) // yields: 1, 3, 6, 10

func Skip

func Skip[T any](s Seq[T], n int) Seq[T]

Skip skips the first n elements and returns the rest.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
iter.Skip(s, 2) // yields: 3, 4, 5

func SkipWhile

func SkipWhile[T any](s Seq[T], pred func(T) bool) Seq[T]

SkipWhile skips elements while the predicate returns true, then yields the rest.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
iter.SkipWhile(s, func(x int) bool { return x < 3 }) // yields: 3, 4, 5

func SortBy

func SortBy[T any](s Seq[T], less func(a, b T) bool) Seq[T]

SortBy returns a sorted sequence using the provided comparison function. Note: This collects all elements into a slice first.

Example:

s := iter.FromSlice([]int{3, 1, 4, 1, 5})
iter.SortBy(s, func(a, b int) bool { return a < b }) // yields: 1, 1, 3, 4, 5

func StepBy

func StepBy[T any](s Seq[T], step int) Seq[T]

StepBy returns every nth element from the sequence.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5, 6})
iter.StepBy(s, 2) // yields: 1, 3, 5

func Take

func Take[T any](s Seq[T], n int) Seq[T]

Take returns the first n elements of the sequence.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
iter.Take(s, 3) // yields: 1, 2, 3

func TakeWhile

func TakeWhile[T any](s Seq[T], pred func(T) bool) Seq[T]

TakeWhile yields elements while the predicate returns true.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
iter.TakeWhile(s, func(x int) bool { return x < 4 }) // yields: 1, 2, 3

func Unique

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

Unique returns a sequence with all duplicate elements removed. Works with any type by using any as the key.

Example:

s := iter.FromSlice([]int{1, 1, 2, 2, 3, 1})
iter.Unique(s) // yields: 1, 2, 3

func UniqueBy

func UniqueBy[T any, K comparable](s Seq[T], key func(T) K) Seq[T]

UniqueBy returns a sequence with consecutive elements removed where the key function returns the same value.

Example:

s := iter.FromSlice([]string{"aa", "bb", "a", "ccc"})
iter.UniqueBy(s, func(s string) int { return len(s) }) // yields: "aa", "a", "ccc"

func Values

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

Values extracts all values from the Seq2 into a Seq.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b"})
iter.Values(s) // yields: "a", "b" (order not guaranteed)

func Windows

func Windows[T any](s Seq[T], n int) Seq[[]T]

Windows returns a sequence of sliding windows of size n.

Example:

s := iter.FromSlice([]int{1, 2, 3, 4, 5})
iter.Windows(s, 3) // yields: [1,2,3], [2,3,4], [3,4,5]

func ZipWith

func ZipWith[A, B, R any](a Seq[A], b Seq[B], f func(A, B) R) Seq[R]

ZipWith combines two sequences using a function, stopping when either sequence ends.

Example:

s1 := iter.FromSlice([]int{1, 2, 3})
s2 := iter.FromSlice([]int{10, 20, 30})
iter.ZipWith(s1, s2, func(a, b int) int { return a + b }) // yields: 11, 22, 33

type Seq2

type Seq2[K, V any] iter.Seq2[K, V]

Seq2 represents a two-value iterator sequence (typically key-value pairs). It calls the yield function for each pair in the sequence. If yield returns false, the iteration should stop.

func Chain2

func Chain2[K, V any](head Seq2[K, V], rest ...Seq2[K, V]) Seq2[K, V]

Chain2 concatenates multiple Seq2 sequences into one.

Example:

s1 := iter.FromMap(map[int]string{1: "a"})
s2 := iter.FromMap(map[int]string{2: "b"})
iter.Chain2(s1, s2) // yields: (1, "a"), (2, "b")

func Context2

func Context2[K, V any](s Seq2[K, V], ctx context.Context) Seq2[K, V]

Context2 wraps a key-value sequence with context cancellation. If the context is cancelled, iteration stops early.

Example:

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
s := iter.Context2(iter.FromMap(map[int]string{1: "a", 2: "b"}), ctx)

func Enumerate

func Enumerate[T any](s Seq[T], start int) Seq2[int, T]

Enumerate returns a sequence of (index, value) pairs starting from the given start index.

Example:

s := iter.FromSlice([]string{"a", "b", "c"})
iter.Enumerate(s, 0) // yields: (0, "a"), (1, "b"), (2, "c")

func Exclude2

func Exclude2[K, V any](s Seq2[K, V], p func(K, V) bool) Seq2[K, V]

Exclude2 returns a new Seq2 containing only pairs that do not satisfy the predicate.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "bb", 3: "ccc"})
iter.Exclude2(s, func(k int, v string) bool { return len(v) > 1 })
// yields pairs where value length <= 1

func Filter2

func Filter2[K, V any](s Seq2[K, V], p func(K, V) bool) Seq2[K, V]

Filter2 returns a new Seq2 containing only pairs that satisfy the predicate.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "bb", 3: "ccc"})
iter.Filter2(s, func(k int, v string) bool { return len(v) > 1 })
// yields pairs where value length > 1

func FilterMap2

func FilterMap2[K, V, K2, V2 any](s Seq2[K, V], f func(K, V) (Pair[K2, V2], bool)) Seq2[K2, V2]

FilterMap2 applies a function to each key-value pair and filters out None results.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "bb", 3: "ccc"})
iter.FilterMap2(s, func(k int, v string) (Pair[int, string], bool) {
  if len(v) > 1 {
    return Pair[int, string]{k*10, strings.ToUpper(v)}, true
  }
  return Pair[int, string]{}, false
}) // yields: (20, "BB"), (30, "CCC")

func FromMap

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

FromMap creates a sequence from a map. The order of key-value pairs is not guaranteed.

Example:

m := map[int]string{1: "a", 2: "b", 3: "c"}
s := iter.FromMap(m)

func FromPairs

func FromPairs[K, V any](pairs []Pair[K, V]) Seq2[K, V]

FromPairs creates a Seq2 from a slice of key-value pairs.

Example:

pairs := []Pair[int, string]{{1, "a"}, {2, "b"}}
s := iter.FromPairs(pairs)

func Inspect2

func Inspect2[K, V any](s Seq2[K, V], fn func(K, V)) Seq2[K, V]

Inspect2 applies a function to each key-value pair for side effects while passing through the original pairs.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b"})
iter.Inspect2(s, func(k int, v string) { fmt.Printf("Processing: %d=%s\n", k, v) })

func Map2

func Map2[K, V, K2, V2 any](s Seq2[K, V], f func(K, V) (K2, V2)) Seq2[K2, V2]

Map2 applies a function to each key-value pair, producing a new Seq2.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b"})
iter.Map2(s, func(k int, v string) (int, string) {
  return k*10, strings.ToUpper(v)
}) // yields: (10, "A"), (20, "B")

func Next2

func Next2[K, V any](s Seq2[K, V]) (K, V, Seq2[K, V], bool)

Next2 extracts the first key-value pair from the sequence and returns the remaining sequence. Returns (key, value, remainingSeq, true) if a pair exists, or (zeroK, zeroV, nil, false) if empty. This is similar to Rust's Iterator::next() method for key-value pairs.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b", 3: "c"})
k, v, rest, ok := iter.Next2(s)
// k = 1, v = "a", ok = true (order not guaranteed for maps)
// rest yields remaining pairs

k2, v2, rest2, ok2 := iter.Next2(rest)
// k2 = 2, v2 = "b", ok2 = true
// rest2 yields remaining pairs

func OrderByKey

func OrderByKey[K, V any](s Seq2[K, V], less func(a, b K) bool) Seq2[K, V]

OrderByKey sorts the sequence by keys using the comparison function.

func OrderByValue

func OrderByValue[K, V any](s Seq2[K, V], less func(a, b V) bool) Seq2[K, V]

OrderByValue sorts the sequence by values using the comparison function.

func Skip2

func Skip2[K, V any](s Seq2[K, V], n int) Seq2[K, V]

Skip2 skips the first n key-value pairs and returns the rest.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b", 3: "c"})
iter.Skip2(s, 1) // yields all pairs except the first

func SortBy2

func SortBy2[K, V any](s Seq2[K, V], less func(a, b Pair[K, V]) bool) Seq2[K, V]

SortBy2 sorts the sequence using the provided comparison function on Pair pairs.

func StepBy2

func StepBy2[K, V any](s Seq2[K, V], step int) Seq2[K, V]

StepBy2 returns every nth key-value pair from the sequence.

Example:

pairs := []Pair[int, string]{{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}}
s := iter.FromPairs(pairs)
iter.StepBy2(s, 2) // yields: (1, "a"), (3, "c")

func Take2

func Take2[K, V any](s Seq2[K, V], n int) Seq2[K, V]

Take2 returns the first n key-value pairs of the sequence.

Example:

s := iter.FromMap(map[int]string{1: "a", 2: "b", 3: "c"})
iter.Take2(s, 2) // yields first 2 pairs

func Zip

func Zip[A, B any](a Seq[A], b Seq[B]) Seq2[A, B]

Zip combines two sequences into pairs, stopping when either sequence ends.

Example:

s1 := iter.FromSlice([]int{1, 2, 3})
s2 := iter.FromSlice([]string{"a", "b"})
iter.Zip(s1, s2) // yields: (1, "a"), (2, "b")

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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