Re: [RFC] Global functions any() and all() on iterables
| From: | Nikita Popov | Date: | Tue, 01 Sep 2020 07:30:45 +0000 |
| Subject: | Re: [RFC] Global functions any() and all() on iterables | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-111760@lists.php.net to get a copy of this message | ||
On Tue, Sep 1, 2020 at 1:56 AM tyson andre <tysonandre775@hotmail.com>
wrote:
> Hi internals,
>
> I've created an RFC for
> https://wiki.php.net/rfc/any_all_on_iterable
>
> This was proposed 2 days ago in
> https://externals.io/message/111711 with
> some interest
> ("Proposal: Adding functions any(iterable $input, ?callable $cb = null,
> int $use_flags=0) and all(...)")
>
> - The $use_flags parameter was removed
>
> The primitives any() and all() are a common part of many programming
> languages and help in avoiding verbosity or unnecessary abstractions.
>
> -
> ”ÙÌ.
> Q“ýè¿ÏN¥Í)òhttps://hackage.haskell.org/package/base-4.14.0.0/docs/Prelude.html#v:any
> -
> ű2²“—�!
> ¾#0Ã5Yhttps://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-
>
> For example, the following code could be shortened significantly
>
> ```
> // Old version
> $satisifes_predicate = false;
> foreach ($item_list as $item) {
> if (API::satisfiesCondition($item)) {
> $satisfies_predicate = true;
> break;
> }
> }
> if (!$satisfies_predicate) {
> throw new APIException("No matches found");
> }
>
> // New version is much shorter and readable
> if (!any($item_list, fn($item) => API::satisfiesCondition($item))) {
> throw new APIException("No matches found");
> }
> ```
>
> That example doesn't have any suitable helpers already in the standard
> library.
> Using array_filter would unnecessarily call satisfiesCondition even after
> the first item was found,
> and array_search doesn't take a callback.
>
> A proposed implementation is
> https://github.com/php/php-src/pull/6053 -
> it takes similar flags and param orders to array_filter().
>
> Thanks,
> - Tyson
>
To be in line with naming conventions, I would suggest calling these
iter_any() and iter_all(), using iter_* as the prefix for our future
additions to the "functions that work on arbitrary iterables" space.
iterable_any() and iterable_all() would work as well, though are
unnecessarily verbose.
Regards,
Nikita