On Sun, Apr 7, 2024 at 8:38 AM Larry Garfield <[email protected]> wrote:
>
> On Sun, Apr 7, 2024, at 10:20 AM, Joshua Rüsweg wrote:
> > Hi
> > I have created an RFC to add the function array_find which returns the
> > first element for which a predicate callback returns true. This is a
> > function which I missed often. Furthermore this type of function is
> > implemented with other programming languages like C++, JavaScript and
> > Rust, too.
> > You can find the RFC at:
> > https://wiki.php.net/rfc/array_find
> > Proof of concept implementation is in:
> > https://github.com/joshuaruesweg/php-src/commit/9f3fc252b92f534d498e5f1e6a463e15f45da208
> > I'm looking forward to your feedback.
> > Cheers
> > Joshua Rüsweg
>
> I'm open to this, but two points that I'm sure someone will bring up:
>
> 1. Should this work on arrays or iterables? This is a long standing
> limitation of PHP. The array operations don't work on iterables, even though
> we've had iterables for 20 years.)
>
> 2. Key handling. It's good that you have looked into this, because I was
> going to mention it. :-) However, I don't think a boolean is the right
> answer, since the question is binary, not true/false. (Those are not the
> same thing.) I think a small return-mode Enum would make more sense here.
IMO, it's better to separate it into two functions because its type is
stable without control flow. For instance:
// Returns K if $b is true, V otherwise.
function array_find(
array<K, V> $array,
callable(V, K): bool $callback,
bool $b = false
) -> K|V;
This isn't stable and requires control-flow to understand the type.
These are simpler:
function array_find(
array<K, V> $array,
callable(V, K): bool $callback
) -> V;
function array_find_key(
array<K, V> $array,
callable(V, K): bool $callback
) -> K;
Naming bikeshedding aside, it's better to have types that are
inferrable without function-specific knowledge of control flow. It
doesn't matter if it's a bool or an enum, it still has problems.
Better to just separate them to different functions.