itertools

package module
v0.0.0-...-86d359e Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2024 License: MIT Imports: 8 Imported by: 0

README

Iterator Library for Go

This library provides a powerful and flexible generic iterator system for Go. It enables functional-style iteration, transformation, and aggregation of collections. It is inspired by the iterator protocols found in Python and Rust.


Table of Contents

  1. Installation
  2. Usage
  3. Features
  4. API Reference
  5. Examples
  6. Contributing
  7. License

Installation

go get -u github.com/amjadjibon/itertools

Usage

Here's a simple example to get you started.

package main

import (
    "fmt"
    "github.com/amjadjibon/itertools"
)

func main() {
    // Create an iterator from a slice
    iter := itertools.ToIter([]int{1, 2, 3, 4, 5})

    // Filter even numbers, map them to their squares, and collect the result
    result := iter.Filter(func(x int) bool { return x%2 == 0 }).
        Map(func(x int) int { return x * x }).
        Collect()

    fmt.Println(result) // Output: [4, 16]
}

Features

  • Chainable API: Combine transformations like Filter, Map, Take, and Drop into one functional-style chain.
  • Laziness: Iterators are lazy; they only compute elements as needed.
  • Composable: Supports operations like Zip, Chain, Union, Intersection, Difference, and Flatten.
  • Collection Methods: Collect items into slices, count them, partition them, and more.
  • Generalized Iterators: Supports all types, as it uses Go's generics.
  • Multiple Data Transformations: Sort, shuffle, reverse, compact, and manipulate iterator contents.

API Reference

Creating an Iterator
  1. From Slice

    iter := itertools.ToIter([]int{1, 2, 3, 4})
    
  2. Custom Sequences

    iter := itertools.NewIterator(1, 2, 3, 4)
    
  3. Repeated Values

    iter := itertools.Repeat(42, 5)
    
  4. Cycle

    iter := itertools.NewIterator(1, 2, 3).Cycle()
    

Iterator Methods

These methods modify or operate on the elements of an iterator.

Method Description
Next() Advances the iterator to the next element.
Current() Returns the current element.
Collect() Collects all elements into a slice.
Each(f func(V)) Applies f to each element.
Filter(f func(V) bool) Yields only elements that satisfy the predicate f.
Map(f func(V) V) Transforms each element using f.
Reverse() Iterates over elements in reverse order.
Take(n int) Takes the first n elements.
Drop(n int) Skips the first n elements.
TakeWhile(f func(V) bool) Yields elements while the predicate f is true.
DropWhile(f func(V) bool) Drops elements while the predicate f is true.
Count() Counts the total number of elements.
First() Returns the first element.
Last() Returns the last element.
Nth(n int) Returns the nth element.
Sort(less func(a, b V) bool) Sorts elements according to less.
Min(less func(a, b V) bool) Returns the minimum element.
Max(less func(a, b V) bool) Returns the maximum element.
Any(f func(V) bool) Returns true if any element satisfies f.
All(f func(V) bool) Returns true if all elements satisfy f.
Find(f func(V) bool) Returns the first element that satisfies f.
Index(f func(V) bool) Returns the index of the first element that satisfies f.
LastIndex(f func(V) bool) Returns the index of the last element that satisfies f.
IsSorted(less func(a, b V) bool) Returns true if the elements are sorted.
Replace(f func(V) bool, replacement V) Replaces elements that satisfy f.
Compact() Removes nil/zero-value elements.
Union(other *Iterator, keyFunc func(V) any) Merges two iterators without duplicates.
Difference(other *Iterator, keyFunc func(V) any) Difference of two iterators.
Intersection(other *Iterator, keyFunc func(V) any) Intersection of two iterators.

Utility Functions
Function Description
Zip(it1, it2) Zips two iterators together.
Zip2(it1, it2, fill) Zips two iterators, filling extra elements with fill.
Fold(it, transform, initial) Reduces the elements using transform.
Sum(it, transform, zero) Sums the elements.
Product(it, transform, one) Computes the product of elements.
ChunkSlice(it, size) Returns slices of size.
Flatten(it1, it2, ...) Flattens multiple iterators into one.
CartesianProduct(it1, it2) Generates Cartesian product of two iterators.

Examples

Basic Usage
// Create an iterator from a slice
iter := itertools.ToIter([]int{1, 2, 3, 4})

// Filter and Map
result := iter.Filter(func(x int) bool { return x%2 == 0 }).
    Map(func(x int) int { return x * 2 }).
    Collect()

fmt.Println(result) // Output: [4, 8]
Sort Elements
iter := itertools.ToIter([]int{3, 1, 4, 2})
sorted := iter.Sort(func(a, b int) bool { return a < b }).Collect()
fmt.Println(sorted) // Output: [1, 2, 3, 4]
Zip Two Iterators
iter1 := itertools.ToIter([]int{1, 2, 3})
iter2 := itertools.ToIter([]string{"a", "b", "c"})

zipped := itertools.Zip(iter1, iter2).Collect()
fmt.Println(zipped) 
// Output: [{1 a} {2 b} {3 c}]
Generate Cartesian Product
iter1 := itertools.ToIter([]int{1, 2})
iter2 := itertools.ToIter([]string{"a", "b"})

cartesian := itertools.CartesianProduct(iter1, iter2).Collect()
fmt.Println(cartesian)
// Output: [{X: 1, Y: "a"} {X: 1, Y: "b"} {X: 2, Y: "a"} {X: 2, Y: "b"}]

Contributing

Contributions are welcome! To get started:

  1. Fork the repository.
  2. Create a new branch for your feature/bugfix.
  3. Submit a pull request.

License

This project is licensed under the MIT License. See the LICENSE file for details.


With this library, you can process collections in a functional, chainable, and lazy manner. From filtering and mapping to complex operations like cartesian products, this iterator system brings the power of iterables to Go. Happy iterating! 🎉

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fold

func Fold[V any, T any](it *Iterator[V], transform func(T, V) T, initial T) T

Fold accumulates the elements of the iterator

func Product

func Product[V any, T Productable](it *Iterator[V], transform func(V) T, one T) T

Product multiplies all elements of the iterator

func Sum

func Sum[V any, T cmp.Ordered](it *Iterator[V], transform func(V) T, zero T) T

Sum adds all elements of the iterator

Types

type Iterator

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

Iterator is a generic iterator that can be used to iterate over any type of sequence

func CartesianProduct

func CartesianProduct[A, B any](it1 *Iterator[A], it2 *Iterator[B]) *Iterator[struct {
	X A
	Y B
}]

CartesianProduct returns an iterator of all pairs of elements from two iterators

func ChunkList

func ChunkList[V any](it *Iterator[V], size int) []*Iterator[V]

ChunkList returns an Iterator of slices of the given size

func ChunkSlice

func ChunkSlice[V any](it *Iterator[V], size int) *Iterator[[]V]

ChunkSlice returns an Iterator of slices of the given size

func Chunks

func Chunks[V any](it *Iterator[V], size int) *Iterator[*Iterator[V]]

Chunks return an list of iterators of slices of the given size

func Flatten

func Flatten[V any](its ...*Iterator[V]) *Iterator[V]

Flatten flattens a list of iterators into a single iterator

func NewIterator

func NewIterator[V any](v ...V) *Iterator[V]

NewIterator creates a new iterator from a sequence function

func Repeat

func Repeat[V any](v V, n int) *Iterator[V]

Repeat returns an Iterator that yields the same element n times

func ToIter

func ToIter[V any](slice []V) *Iterator[V]

ToIter creates an Iterator from a slice

func Zip

func Zip[A, B any](it1 *Iterator[A], it2 *Iterator[B]) *Iterator[struct {
	First  A
	Second B
}]

Zip combines two iterators element-wise into a single iterator of pairs.

func Zip2

func Zip2[A, B any](it1 *Iterator[A], it2 *Iterator[B], _ struct {
	First  A
	Second B
}) *Iterator[struct {
	First  A
	Second B
}]

Zip2 combines two iterators element-wise into a single iterator of pairs. If one iterator is longer than the other, the shorter iterator is extended with the fill value.

func (*Iterator[V]) All

func (it *Iterator[V]) All(predicate func(V) bool) bool

All returns true if all elements in the Iterator satisfy the predicate

func (*Iterator[V]) Any

func (it *Iterator[V]) Any(predicate func(V) bool) bool

Any returns true if any element in the Iterator satisfies the predicate

func (*Iterator[V]) AssertEq

func (it *Iterator[V]) AssertEq(expected []V, predicate func(V, V) bool) bool

AssertEq asserts that the elements in the Iterator are equal to the expected elements

func (*Iterator[V]) Chain

func (it *Iterator[V]) Chain(other *Iterator[V]) *Iterator[V]

Chain concatenates two iterators

func (*Iterator[V]) Collect

func (it *Iterator[V]) Collect() []V

Collect collects all elements from the Iterator into a slice.

func (*Iterator[V]) Compact

func (it *Iterator[V]) Compact() *Iterator[V]

Compact removes the nil elements from the Iterator

func (*Iterator[V]) CompactWith

func (it *Iterator[V]) CompactWith(zero V) *Iterator[V]

CompactWith removes the elements that are equal to the zero value of the type

func (*Iterator[V]) Count

func (it *Iterator[V]) Count() int

Count returns the number of elements in the Iterator

func (*Iterator[V]) Current

func (it *Iterator[V]) Current() V

Current returns the current element of the iterator

func (*Iterator[V]) Cycle

func (it *Iterator[V]) Cycle() *Iterator[V]

Cycle returns an Iterator that cycles through the elements of the Iterator indefinitely

func (*Iterator[V]) Difference

func (it *Iterator[V]) Difference(other *Iterator[V], keyFunc func(V) any) *Iterator[V]

Difference returns an Iterator that yields elements that are present in the first iterator but not in the second

func (*Iterator[V]) Drop

func (it *Iterator[V]) Drop(n int) *Iterator[V]

Drop returns an Iterator that skips the first n elements of the Iterator

func (*Iterator[V]) DropWhile

func (it *Iterator[V]) DropWhile(predicate func(V) bool) *Iterator[V]

DropWhile returns an Iterator that skips elements while the predicate is true

func (*Iterator[V]) Each

func (it *Iterator[V]) Each(f func(V))

Each applies a function to each element of the Iterator.

func (*Iterator[V]) Filter

func (it *Iterator[V]) Filter(predicate func(V) bool) *Iterator[V]

Filter returns an Iterator that only yields elements that satisfy the predicate

func (*Iterator[V]) Find

func (it *Iterator[V]) Find(predicate func(V) bool) (V, bool)

Find returns the first element that satisfies the predicate

func (*Iterator[V]) First

func (it *Iterator[V]) First() V

First returns the first element of the Iterator

func (*Iterator[V]) GroupBy

func (it *Iterator[V]) GroupBy(keyFunc func(V) string) map[string][]V

GroupBy groups elements by a key function into a map.

func (*Iterator[V]) Index

func (it *Iterator[V]) Index(predicate func(V) bool) int

Index returns the index of the first element that satisfies the predicate

func (*Iterator[V]) Intersection

func (it *Iterator[V]) Intersection(other *Iterator[V], keyFunc func(V) any) *Iterator[V]

Intersection returns an Iterator that yields elements that are present in both iterators

func (*Iterator[V]) IsSorted

func (it *Iterator[V]) IsSorted(less func(a, b V) bool) bool

IsSorted returns true if the elements in the Iterator are sorted in ascending order

func (*Iterator[V]) Last

func (it *Iterator[V]) Last() V

Last returns the last element of the Iterator

func (*Iterator[V]) LastIndex

func (it *Iterator[V]) LastIndex(predicate func(V) bool) int

LastIndex returns the index of the last element that satisfies the predicate

func (*Iterator[V]) Map

func (it *Iterator[V]) Map(f func(V) V) *Iterator[V]

Map transforms each element in the Iterator using a provided function.

func (*Iterator[V]) Max

func (it *Iterator[V]) Max(less func(a, b V) bool) (V, bool)

Max returns the maximum element in the Iterator using the provided less function

func (*Iterator[V]) Min

func (it *Iterator[V]) Min(less func(a, b V) bool) (V, bool)

Min returns the minimum element in the Iterator using the provided less function

func (*Iterator[V]) Next

func (it *Iterator[V]) Next() bool

Next advances the iterator and returns true if there is a next element.

func (*Iterator[V]) Nth

func (it *Iterator[V]) Nth(n int) V

Nth returns the nth element of the Iterator

func (*Iterator[V]) Partition

func (it *Iterator[V]) Partition(predicate func(V) bool) (matched *Iterator[V], unmatched *Iterator[V])

Partition returns two Iterators, one with elements that satisfy the predicate and one with elements that don't

func (*Iterator[V]) Replace

func (it *Iterator[V]) Replace(predicate func(V) bool, replacement V) *Iterator[V]

Replace replaces all elements that satisfy the predicate with the replacement

func (*Iterator[V]) ReplaceAll

func (it *Iterator[V]) ReplaceAll(replacement V) *Iterator[V]

ReplaceAll replaces all elements with the replacement

func (*Iterator[V]) Reverse

func (it *Iterator[V]) Reverse() *Iterator[V]

Reverse returns an Iterator that iterates over the elements in reverse order

func (*Iterator[V]) Shuffle

func (it *Iterator[V]) Shuffle() *Iterator[V]

Shuffle returns an Iterator that yields elements in a random order

func (*Iterator[V]) Sort

func (it *Iterator[V]) Sort(less func(a, b V) bool) *Iterator[V]

Sort returns an Iterator with elements sorted in ascending order using the provided less function.

func (*Iterator[V]) StepBy

func (it *Iterator[V]) StepBy(n int) *Iterator[V]

StepBy returns an Iterator that yields every nth element

func (*Iterator[V]) String

func (it *Iterator[V]) String() string

String returns a string representation of the Iterator

func (*Iterator[V]) Take

func (it *Iterator[V]) Take(n int) *Iterator[V]

Take returns an Iterator that yields the first n elements of the Iterator

func (*Iterator[V]) TakeWhile

func (it *Iterator[V]) TakeWhile(predicate func(V) bool) *Iterator[V]

TakeWhile returns an Iterator that yields elements while the predicate is true

func (*Iterator[V]) ToLower

func (it *Iterator[V]) ToLower() *Iterator[V]

ToLower converts all elements to lowercase if they are strings and if not, it leaves them unchanged in the Iterator

func (*Iterator[V]) ToUpper

func (it *Iterator[V]) ToUpper() *Iterator[V]

ToUpper converts all elements to uppercase if they are strings and if not, it leaves them unchanged in the Iterator

func (*Iterator[V]) TrimSpace

func (it *Iterator[V]) TrimSpace() *Iterator[V]

TrimSpace trims the whitespace from all elements if they are strings and if not, it leaves them unchanged in the Iterator

func (*Iterator[V]) Union

func (it *Iterator[V]) Union(other *Iterator[V], keyFunc func(V) any) *Iterator[V]

Union returns an Iterator that yields elements from both iterators without duplicates

func (*Iterator[V]) Unique

func (it *Iterator[V]) Unique(keyFunc func(V) any) *Iterator[V]

Unique returns an Iterator with only unique elements

type Productable

type Productable interface {
	constraints.Integer | constraints.Float | constraints.Complex
}

Jump to

Keyboard shortcuts

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