Re: Proposal: Adding functions any(iterable $input, ?callable $cb = null, int $use_flags=0) and all(...)
| From: | tyson andre | Date: | Sun, 30 Aug 2020 15:40:39 +0000 |
| Subject: | Re: Proposal: Adding functions any(iterable $input, ?callable $cb = null, int $use_flags=0) and all(...) | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-111724@lists.php.net to get a copy of this message | ||
Hi Josh Bruce,
> The compelling feature here for me is the idea of an “array walker” that can be broken out
> of.
>
> all() could be and() at which point this should be equivalent.
Yes, you can write
all($set, $predicate_fn) as !any($set, fn($x) =>
!$predicate_fn($x)) or some other common primitive such as and(),
but as an end user or a reviewer of code, I really don't want to do the latter, which is why I
proposed adding both of these. (also see below snippet)
> Would there also be an xor() or equivalent?? one() or something??
>
> If (count(array_filter($collection, “is_int”)) === 1)
I don't plan to expand the scope of the RFC more - there are various features such as none() or
exactly_n(int $n, $iterable, $callback) I'm also not proposing.
RFC votes require a 2/3 majority and I'd think more would advocate doing one() in userland than
any()
> Here’s an implementation of each() I made that allows for breaking by the caller using a
> passed by ref third argument in the
> closure: https://github.com/8fold/php-shoop/blob/2a8b6fc41c545ff71690562ac2f35a12457b1514/src/Traits/EachImp.php -
> I’ve since deprecated that functionality and not sure if I’ll be bringing that functionality
> back because of frustrations and philosophical arguments with myself. :)
Modifying a reference instead could be done to achieve the same result
as setting a reference boolean in the cases where you needed to know what element it was.
```
if (any($values, function ($v) use (&$result) {
if ($v->satisfiesPredicate()) {$result = $v; return true;} return false; })
) {
process($result);
}
```
> Part of me wishes the “all()” and “any()” names were more descriptive of what’s going
> on.
>
> When I call for “all” in a database or some ORM, I *get* all - I’m not verifying “all
> pass [a predicate]”.
The naming is based on mathematical notation.
- any($list, $predicate) "Determines whether any element of the iterable satisfies the
predicate."
- all($list, $predicate) "Determines whether all elements of the iterable satisfy the
predicate."
every() and some() are alternative names,
but all()/any() are my preference and appear more commonly used elsewhere.
- https://hackage.haskell.org/package/base-4.14.0.0/docs/Prelude.html#v:any
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
- https://docs.python.org/3/library/functions.html#all
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#allMatch-java.util.function.Predicate-
Thanks,
- Tyson