$ show lstrojny/functional-php
This is a PHP library providing a comprehensive set of functional programming primitives for arrays and Traversables. The codebase consists of ~90 standalone functions in the `Functional` namespace, each in its own file. Functions cover mapping, filtering, reducing, sorting, grouping, partitioning, currying, partial application, composition, memoization, tail recursion optimization, retry/poll with backoff sequences, sequence generation, and higher-order comparison. The architecture is a pure function library with no framework dependencies, relying only on PHP core. Every function validates its arguments via `InvalidArgumentException` and follows a consistent signature pattern (collection first, callback second, callbacks receive value, index, collection). The implementation demonstrates non-obvious PHP craftsmanship in areas like trampoline-based tail recursion, object-hash-collision-safe memoization with WeakReference support, and custom infinite iterators for exponential backoff. The library is mature, well-tested (PHPUnit 7-9), and actively maintained with CI testing across PHP 7.1 to 8.5.
The LLM identified 4 files worth highlighting for reuse:
Implements tail recursion optimization using a trampoline pattern. The returned closure queues recursive calls and processes them iteratively, preventing stack overflow on deep recursion. Self-contained and can be applied to any tail-recursive callable. Demonstrates advanced closure and recursion management in PHP.
Memoizes any callable with support for arguments and custom keys. Uses a sophisticated key generation via `value_to_key` that handles object identity, arrays, and even handles `spl_object_hash` collisions (via WeakReference in PHP 7.4+). Includes reset capability and deprecation warnings for old callable-key usage. Reusable as a standalone caching utility.
Generates deterministic string keys from arbitrary PHP values (including objects, arrays, resources). Handles object identity using `spl_object_hash` with collision detection (WeakReference for PHP 7.4+, static reference for older versions). Recursively traverses arrays and Traversables. Used internally by `memoize` but is a standalone utility for any scenario requiring repeatable hashing of PHP data.
A concise, elegant implementation of argument flipping. Returns a new callable that reverses the order of arguments using `array_reverse` on `func_get_args`. Only a few lines but demonstrates the power of variadic arguments and closures. Perfectly reusable for any function where argument order needs inversion (e.g., to enable currying on functions like `filter`).