LimitIterator / CallbackFilterIterator / RegexIterator
new LimitIterator(Iterator $it, int $offset = 0, int $limit = -1) / new CallbackFilterIterator(Iterator $it, callable $callback) / new RegexIterator(Iterator $it, string $pattern)
The SPL decorator trio layered on iterators: limit (LimitIterator), callback-filter (CallbackFilterIterator), regex-filter (RegexIterator) - a lazy pipeline, complementing the concrete structures SplStack/SplQueue.
C C23
#include <stdio.h>
#include <string.h>
/* C has no iterators - a hand-written loop fuses the three decorators
(filter -> regex -> limit) into one pass over the array */
int main(void) {
const char *data[] = {"apple-01", "avocado-04", "apricot-01",
"banana-02", "cherry-03"};
int n = 0;
for (int i = 0; i < 5 && n < 2; i++) {
const char *v = data[i];
if (v[0] != 'a') continue; /* CallbackFilterIterator */
size_t len = strlen(v);
if (!(len >= 3 && (strcmp(v + len - 3, "-01") == 0 ||
strcmp(v + len - 3, "-04") == 0))) {
continue; /* RegexIterator */
}
printf("%s\n", v); /* LimitIterator stops at 2 */
n++;
}
return 0;
}
apple-01 avocado-04
C++ C++26
#include <iostream>
#include <string>
#include <vector>
#include <ranges>
int main() {
std::vector<std::string> data = {"apple-01", "avocado-04", "apricot-01",
"banana-02", "cherry-03"};
// C++20 ranges: decorators become composable lazy views
auto pipe = data
| std::views::filter([](const std::string& v) { return v.starts_with('a'); })
| std::views::filter([](const std::string& v) {
return v.ends_with("-01") || v.ends_with("-04"); // RegexIterator analogue
})
| std::views::take(2); // LimitIterator
for (const auto& v : pipe) { // nothing runs until this loop pulls
std::cout << v << "\n";
}
return 0;
}
apple-01 avocado-04
C# v11.0.100
using System;
using System.Linq;
using System.Text.RegularExpressions;
class MainClass {
static void Main() {
var data = new[] { "apple-01", "avocado-04", "apricot-01",
"banana-02", "cherry-03" };
// LINQ: Where/Take are the decorator trio, deferred until enumerated
foreach (var v in data
.Where(v => v.StartsWith("a")) // CallbackFilterIterator
.Where(v => Regex.IsMatch(v, "-0[14]$")) // RegexIterator
.Take(2)) { // LimitIterator
System.Console.WriteLine(v);
}
}
}
apple-01 avocado-04
Go v1.27.4
package main
import (
"fmt"
"iter"
"regexp"
"strings"
)
// Go 1.23+ iter.Seq composes iterator pipelines like the SPL decorators
func pipeline(data []string) iter.Seq[string] {
re := regexp.MustCompile(`-0[14]$`)
return func(yield func(string) bool) {
n := 0
for _, v := range data {
if !strings.HasPrefix(v, "a") { // CallbackFilterIterator
continue
}
if !re.MatchString(v) { // RegexIterator
continue
}
if n >= 2 { // LimitIterator
return
}
n++
if !yield(v) {
return
}
}
}
}
func main() {
for v := range pipeline([]string{"apple-01", "avocado-04", "apricot-01",
"banana-02", "cherry-03"}) {
fmt.Println(v)
}
}
apple-01 avocado-04
Java v27.0.1
import java.util.List;
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
List<String> data = List.of("apple-01", "avocado-04", "apricot-01",
"banana-02", "cherry-03");
// Stream: filter/limit form the same lazy decorator pipeline
data.stream()
.filter(v -> v.startsWith("a")) // CallbackFilterIterator
.filter(v -> Pattern.compile("-0[14]$").matcher(v).find()) // RegexIterator
.limit(2) // LimitIterator
.forEach(System.out::println);
}
}
apple-01 avocado-04
JavaScript v26.13.1
// no built-in iterator decorators - a generator fuses the three roles
function* pipeline(data) {
let n = 0;
for (const v of data) {
if (!v.startsWith('a')) continue; // CallbackFilterIterator
if (!/-0[14]$/.test(v)) continue; // RegexIterator
if (n++ >= 2) return; // LimitIterator
yield v;
}
}
for (const v of pipeline(['apple-01', 'avocado-04', 'apricot-01',
'banana-02', 'cherry-03'])) {
console.log(v);
}
apple-01 avocado-04
PHP v8.6.0
// decorator pipeline on ArrayIterator: filter -> regex -> limit
$data = new ArrayIterator(['apple-01', 'avocado-04', 'apricot-01',
'banana-02', 'cherry-03']);
$filtered = new CallbackFilterIterator($data, fn($v) => str_starts_with($v, 'a'));
$regexed = new RegexIterator($filtered, '/-0[14]$/');
$limited = new LimitIterator($regexed, 0, 2);
foreach ($limited as $k => $v) {
echo $k, ':', $v, "\n"; // original keys survive the decorators
}
// laziness: each stage pulls from the previous one only on demand
0:apple-01 1:avocado-04
Python v3.15.2
import itertools
import re
# Python's native counterpart family: lazy iterators all the way down
data = iter(['apple-01', 'avocado-04', 'apricot-01', 'banana-02', 'cherry-03'])
filtered = filter(lambda v: v.startswith('a'), data) # CallbackFilterIterator
regexed = filter(lambda v: re.search(r'-0[14]$', v), filtered) # RegexIterator
limited = itertools.islice(regexed, 2) # LimitIterator
for v in limited:
print(v)
apple-01 avocado-04
Rust v1.99.1
fn main() {
let data = ["apple-01", "avocado-04", "apricot-01", "banana-02", "cherry-03"];
// Rust's iterator adapters are the same decorators, zero-cost inlined
let pipe = data
.iter()
.filter(|v| v.starts_with('a')) // CallbackFilterIterator
.filter(|v| v.ends_with("-01") || v.ends_with("-04")) // RegexIterator analogue
.take(2); // LimitIterator
for v in pipe {
println!("{v}"); // lazy: adapters run only as the loop pulls
}
}
apple-01 avocado-04
TypeScript v26.13.1
function* pipeline(data: string[]): Generator<string> {
let n = 0;
for (const v of data) {
if (!v.startsWith('a')) continue; // CallbackFilterIterator
if (!/-0[14]$/.test(v)) continue; // RegexIterator
if (n++ >= 2) return; // LimitIterator
yield v;
}
}
for (const v of pipeline(['apple-01', 'avocado-04', 'apricot-01',
'banana-02', 'cherry-03'])) {
console.log(v);
}
apple-01 avocado-04
Language differences
C: no iterators - decorator semantics fuse into one hand-written loop (example); "decorator-style iteration" here is pure control flow.
C++: C++20 range views are the decorators (example) - filter/take compose lazily and the pipeline runs only during traversal; there is no standard regex view, so the example uses suffix comparison as RegexIterator's honest analogue.
C#: LINQ Where/Take with deferred execution (example) - Regex.IsMatch is the RegexIterator analogue; a chain of Where calls is stacked decorators.
Go: iter.Seq since 1.23 (example) - native for-range support, the yield protocol is the decorator pipeline; before that you hand-rolled closures or channels.
Java: Stream filter/limit (example) - note a Stream is single-use, reuse needs a fresh stream(); Iterator itself has no decorators, IteratorIterator must be hand-written.
JavaScript: no built-in decorators - generator functions are the idiom (example); array filter/slice are the eager variant (computes everything up front), the lazy variant needs a generator.
PHP: THE core of this entry - decorators wrap the iterator layer upon layer and foreach touches only the outermost; lazy: each stage pulls from the inner one on demand; original keys survive the decorators (keys 0/1 in the example output); RegexIterator's default MATCH mode filters by "does it match", while GET_MATCH/REPLACE modes rewrite values; LimitIterator's offset needs the inner iterator to support rewind+seek; complementary to SplStack/SplQueue: those are concrete structures, these are behavior decorators.
Python: filter + itertools.islice (example) - fully lazy; re.search is the RegexIterator; generator expressions are an equivalent alternative.
Rust: iterator adapters (example) - .filter().take() is zero-cost, compiling to the hand-written loop; with the regex crate, swap the closure for re.is_match.
TypeScript: the same generator solution as JS (example); Iterable<T> plus hand-written filter/take higher-order functions is another common shape.