用户可利用该项目高效处理序列数据,实现复杂迭代逻辑。它提供高级迭代器功能,含生成器、索引、预览、组合学、去重等适配器,以及折叠、聚合、分组等终止操作,还支持并行处理与类型安全迭代。【此简介由AI生成】
Access rate limit exceeded. Please log in to continue.
Introduction
A lazy iterator toolkit for the Cangjie language, inspired by Rust's itertools. Provides advanced iterator functionality not available in the standard library Iterator<T>, including generators, indexing, peeking, combinatorics, deduplication, conditional processing, and other lazy adapters, as well as fold, search, aggregate, grouping, sorting, and comparison terminal operations.
Features
- Generator Adapters:
iterate,repeatN,unfoldfor infinite/finite sequence generation - Indexing & Position:
enumerate,positions,withPositionfor position marking - Peeking & Putback:
multipeek,putBack,putBackNfor flexible iteration control - Combinatorics Adapters: Cartesian product, combinations, permutations, powerset
- Deduplication & Conditional: Global dedup, consecutive dedup, conditional termination
- Rich Terminal Operations: Fold, search, aggregate, grouping, sorting, comparison
- Parallel Iterators (v2.0): Efficient parallel processing using coroutines
- Type-Safe Iterators (v2.0): NonEmptyIterator, SortedIterator, UniqueIterator
- Advanced Statistics (v2.0): Median, percentile, mode, covariance, correlation, histogram
- Time Series Operations (v2.0): Moving average, exponential moving average, lag, lead
- Debug Tools (v2.0): Profiling, tracing
v2.0.0 New Features
Standard Library Ecosystem Integration
Collectors Module (stdlib/collectors.cj) Provides functionality to collect iterators into standard library collection types:
- toHashSet: Collect to HashSet with automatic deduplication
- toHashMap: Collect key-value pairs to HashMap
- toHashMapBy: Collect to HashMap using key/value functions
- toLinkedList: Collect to LinkedList (preserves order)
- collectToString: Collect character iterator to string
- fromArrayList/fromHashSet/fromHashMap: Convert collections to iterators
Collection Extension Methods (stdlib/collection_ext.cj) Adds itertools-style extension methods to standard library collection types:
- ArrayList:
iter(),iterChunks(),iterWindows(),iterEnumerate(),iterReverse() - HashMap:
iterKeys(),iterValues(),iterEntries() - HashSet:
iter(),iterDifference()
Comparable Interface Integration (stdlib/comparable_ext.cj) Provides convenient operations for types implementing Comparable:
- sorted: Natural sorting
- minValue/maxValue: Get minimum/maximum value
- minmaxValue: Get both minimum and maximum values
Option/Result Iterators (stdlib/option_iter.cj, result_iter.cj) Treat Option and Result types as iterators:
- optionIter: Convert Option to 0/1 element iterator
- resultOkIter/resultErrIter: Iterators for Result's Ok/Err values
String Iterators (stdlib/string_iter.cj) Lazy iteration operations for strings:
- stringChars: Character iterator
- stringLines: Line iterator
- stringWords: Word iterator
- stringSplit: Split iterator
Slice and Reverse Iterators (stdlib/slice_iter.cj, collection_ext.cj)
- sliceIter: Array slice iterator with negative index support
- reverseIter/reversed: Reverse iterator
Lazy String Builder (stdlib/lazy_string.cj)
- LazyJoiner: Lazy string joiner
- lazyJoin/lazyFormat: Lazy string building functions
Parallel Collectors (parallel/par_collectors.cj)
- parCollectToArrayList: Parallel collect to ArrayList
- parCollectToHashSet: Parallel collect to HashSet
- parCollectToHashMap: Parallel collect to HashMap
Lazy Evaluation Optimization
Fusion Adapters (adapters/fusion.cj) Provides iterator fusion operations, combining multiple consecutive operations into a single traversal to reduce intermediate allocations:
- filterMap: map+filter fusion, applies function f to each element, keeps Some values, filters None
- mapFilter: filter+map fusion, applies map first, then filter
- composeMap: map+map fusion, combines two transformations into single g(f(x))
- andFilter: filter+filter fusion, merges two predicates into single test p1(x) && p2(x)
- slice: skip+take fusion, efficiently gets [start, end) range of sequence
Short-Circuit Counting Operations (terminals/short_circuit.cj) Provides short-circuit operations with counting, returning result and actual elements checked:
- anyWithCount: any operation with count, returns (Bool, Int64)
- allWithCount: all operation with count, returns (Bool, Int64)
- findWithCount: find operation with count, returns (Option, Int64)
- containsWithCount: contains operation with count, returns (Bool, Int64)
Lazy Verification Tools (adapters/lazy_debug.cj) Provides tools for verifying and debugging lazy evaluation behavior:
- countingIterator: Counting iterator, tracks next() call count
- assertLazy: Assert lazy iterator, detects over-consumption
Advanced Statistics
- Median and Percentile:
median,medianFloat,percentile,percentileFloat - Mode:
mode- returns most frequently occurring element - Covariance and Correlation:
covariance,correlation- analyze relationship between two sequences - Histogram:
histogram,histogramBy- data distribution visualization
Time Series Operations
- Moving Average:
movingAverage,movingAverageInt- simple moving average - Exponential Moving Average:
exponentialMovingAverage- gives higher weight to recent data - Lag/Lead:
lag,lead- access elements n positions before/after
Parallel Iterators
- parMap: Parallel map, preserves output order
- parFilter: Parallel filter, preserves output order
- parReduce: Parallel reduce, uses divide-and-conquer strategy
- ParallelConfig: Parallel execution configuration
Type-Safe Iterators
- NonEmptyIterator: Compile-time guarantee of at least one element
firstValue(),reduceValue(),lastValue()always succeed
- SortedIterator: Compile-time guarantee of sorted elements
merge(),union(),intersection(),binarySearch()optimized operations
- UniqueIterator: Compile-time guarantee of no duplicate elements
containsValue()O(1) lookup
Functional Programming Enhancements
- scan1: Scan adapter without initial value
- unfoldN: Finite unfold generator, produces exactly n elements
- converge: Convergence iteration generator
- fixpoint, fixpointFloat: Find fixed point
Debug Tools
- profile: Profiling adapter, measures iterator operation performance
- trace: Tracing adapter, logs each element flow
Usage
// Basic types and collection operations
import itertools.*
// Lazy adapters
import itertools.adapters.*
// Terminal operations
import itertools.terminals.*
// Parallel iterators (v2.0 new)
import itertools.parallel.*
// Type-safe iterators (v2.0 new)
import itertools.typed.*
// Standard library integration (v2.0 new)
import itertools.stdlib.*
Function List
Lazy Adapters (itertools.adapters)
| Module | Function | Description |
|---|---|---|
| generators | iterate(init, f) |
Generate infinite sequence from initial value and function |
| generators | repeatN(val, n) |
Repeat value n times |
| generators | unfold(init, f) |
Unfold sequence from state function |
| indexing | enumerate(xs) |
Add index to each element |
| indexing | positions(xs, pred) |
Return all positions satisfying predicate |
| indexing | withPosition(xs) |
Mark element position (Only/First/Middle/Last) |
| peeking | multipeek(xs) |
Multi-step peeking iterator |
| peeking | peekNth(xs, n) |
Peek nth element |
| peeking | putBack(xs) |
Single element putback iterator |
| peeking | putBackN(xs) |
Multi-element putback iterator (LIFO) |
| grouping | chunks(xs, size) |
Chunk by fixed size |
| grouping | windows(xs, size) |
Sliding window |
| combining | multizip(xss) |
Multi-sequence zip |
| combinatorics | combinations(xs, k) |
k-combinations |
| combinatorics | permutations(xs, k) |
k-permutations |
| combinatorics | powerset(xs) |
Powerset |
| dedup | distinct(xs) |
Global deduplication |
| conditional | whileSome(xs) |
Until None encountered |
| conditional | mapOk(xs, f) |
Map Ok values in Result stream |
| stepping | stepBy(xs, step) |
Step iterator |
| statistics | runningSum(xs) |
Running sum iterator |
| statistics | movingAverage(xs, window) |
Simple moving average |
| set_ops | unionBy(xs, ys, less) |
Sorted sequence union |
| fusion | filterMap(xs, f) |
map+filter fusion |
| fusion | slice(xs, start, end) |
skip+take fusion |
Terminal Operations (itertools.terminals)
| Module | Function | Description |
|---|---|---|
| search | exactlyOne(xs) |
Assert exactly one element |
| search | contains(xs, elem) |
Check if element exists |
| search | allEqual(xs) |
Check if all elements equal |
| aggregate | counts(xs) |
Element frequency statistics |
| aggregate | minmax(xs, less) |
Get min and max in single traversal |
| position | positionMinBy(xs, less) |
Find minimum value position |
| sort_merge | sortedBy(xs, less) |
Sort using comparison function |
| sort_merge | kSmallest(xs, k, less) |
Return k smallest elements (heap optimized O(n log k)) |
| grouping | groupBy(xs, keyFn) |
Group by key function |
| result_ops | foldOk(xs, init, f) |
Fold Ok values in Result stream |
| result_ops | tryCollect(xs) |
Collect Result stream to Result<ArrayList, E> |
| try_ops | tryForEach(xs, f) |
Apply function to each element, stop on Err |
| statistics | average(xs) |
Calculate arithmetic mean |
| statistics | median(xs) |
Calculate median |
| statistics | correlation(xs, ys) |
Calculate Pearson correlation coefficient |
Parallel Iterators (itertools.parallel) - v2.0 New
| Module | Function | Description |
|---|---|---|
| parallel_iter | ParallelConfig |
Parallel execution configuration |
| par_map | parMap(xs, f, config) |
Parallel map |
| par_filter | parFilter(xs, pred, config) |
Parallel filter |
| par_reduce | parReduce(xs, f, config) |
Parallel reduce |
Type-Safe Iterators (itertools.typed) - v2.0 New
| Module | Function/Type | Description |
|---|---|---|
| non_empty | NonEmptyIterator<T> |
Non-empty iterator type |
| non_empty | nonEmpty(xs) |
Create non-empty iterator |
| sorted | SortedIterator<T> |
Sorted iterator type |
| sorted | assertSorted(xs, less) |
Assert iterator is sorted |
| unique | UniqueIterator<T> |
Unique element iterator type |
| unique | assertUnique(xs) |
Assert iterator elements are unique |
Standard Library Integration (itertools.stdlib) - v2.0 New
| Module | Function/Type | Description |
|---|---|---|
| collectors | toHashSet(xs) |
Collect to HashSet |
| collectors | toHashMap(xs) |
Collect key-value pairs to HashMap |
| collection_ext | ArrayList.iter() |
ArrayList iterator |
| collection_ext | HashMap.iterKeys() |
Key iterator |
| comparable_ext | sorted(xs) |
Comparable natural sort |
| option_iter | optionIter(opt) |
Option to iterator |
| string_iter | stringChars(s) |
Character iterator |
| string_iter | stringLines(s) |
Line iterator |
| lazy_string | lazyJoin(xs, sep, fmt) |
Lazy join |
Basic Types (itertools)
| Type | Description |
|---|---|
Position |
Element position marker: Only, First, Middle, Last |
Diff<T> |
Sequence difference: Equal, Longer, Shorter, FirstMismatch |
Result<T, E> |
Success or failure result |
Either<L, R> |
One of two possible types |
Examples
import itertools.*
import itertools.adapters.*
import itertools.terminals.*
main() {
// Generate Fibonacci sequence
let fib = iterate((0, 1), {(a, b) => (b, a + b)})
.map({(a, _) => a})
.take(10)
|> toArrayList
// fib = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
// Indexed filtering
let indexed = enumerate([10, 20, 30, 40, 50].iterator())
|> toArrayList
// indexed = [(0, 10), (1, 20), (2, 30), (3, 40), (4, 50)]
// Element frequency statistics
let freq = counts([1, 2, 1, 3, 1, 2].iterator())
// freq = {1: 3, 2: 2, 3: 1}
// === v2.0 New Features Examples ===
// Advanced statistics - median
let med = median([1, 3, 5, 7, 9].iterator())
// med = Some(5.0)
// Time series - moving average
let ma = movingAverage([1.0, 2.0, 3.0, 4.0, 5.0].iterator(), 3) |> toArrayList
// ma = [2.0, 3.0, 4.0]
// Parallel iterator - parMap
let doubled = parMap([1, 2, 3, 4, 5].iterator(), {x => x * 2}, ParallelConfig.default())
// doubled = [2, 4, 6, 8, 10]
// Type-safe iterator - NonEmptyIterator
let ne = nonEmpty([1, 2, 3].iterator())
match (ne) {
case Some(iter) =>
let first = iter.firstValue() // 1, not Option
case None => ()
}
// Standard library integration - collect to HashSet
let set = toHashSet([1, 2, 2, 3, 3, 3].iterator())
// set = {1, 2, 3}
// String line iterator
let lines = stringLines("hello\nworld\nfoo") |> toArrayList
// lines = ["hello", "world", "foo"]
}
Project Architecture
src/
├── lib.cj # Library entry and documentation
├── types.cj # Basic type definitions
├── collect.cj # Collection operations
├── internal/
│ └── heap.cj # Internal heap implementation
├── adapters/ # Lazy adapters
├── terminals/ # Terminal operations
├── parallel/ # Parallel iterators (v2.0)
├── stdlib/ # Standard library integration (v2.0)
└── typed/ # Type-safe iterators (v2.0)
Build and Test
# Build
cjpm build
# Run tests
cjpm test
Performance Optimization
The itertools library implements multiple performance optimizations for efficient large-scale data processing:
Heap Operation Optimization
- O(1) space pop operation:
BinaryHeap.pop()uses logical size tracking - Single-assignment siftDown: Heap sift-down uses single assignment instead of multiple swaps
- Efficient Top-K:
kSmallest/kLargestuse heap optimization, O(n log k) time complexity
Sliding Window Optimization
- RingBuffer implementation:
slidingWindowandmapWindowsuse ring buffer - O(step) window sliding: Window sliding optimized from O(windowSize) to O(step)
Parallel Iterator Optimization
- Adaptive chunking: Automatically adjusts chunk size based on data volume
- Sequential fallback: Small datasets automatically fall back to sequential processing
- Configurable thresholds:
ParallelConfigsupportsminChunkSize,adaptiveChunking,sequentialThreshold
Constraints and Limitations
- Requires Cangjie 1.0.4 (cjnative runtime)
- Combinatorics operations may use more memory with large inputs
- Infinite iterators (like
iterate,cycle) need to be used withtake
License
Contributing
Welcome to submit Issues / PRs to help improve the lazy iterator ecosystem.
Introduction
用户可利用该项目高效处理序列数据,实现复杂迭代逻辑。它提供高级迭代器功能,含生成器、索引、预览、组合学、去重等适配器,以及折叠、聚合、分组等终止操作,还支持并行处理与类型安全迭代。【此简介由AI生成】
Customize your domain