Re: Proposal: Adding functions any(iterable $input, ?callable $cb = null, int $use_flags=0) and all(...)
| From: | Marco Pivetta | Date: | Sun, 30 Aug 2020 03:46:36 +0000 |
| Subject: | Re: Proposal: Adding functions any(iterable $input, ?callable $cb = null, int $use_flags=0) and all(...) | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-111716@lists.php.net to get a copy of this message | ||
Hey Tyson,
<http://ocramius.github.com/>
On Sat, Aug 29, 2020 at 10:24 PM tyson andre <tysonandre775@hotmail.com>
wrote:
> Hi internals,
>
> The primitives any() and all() are a common part of many programming
> languages and help in avoiding verbosity or unnecessary abstractions.
>
> -
>
> 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-
>
> For example, the following code could be shortened significantly
>
> ```
> // Old version
> $satisifes_predicate = false;
> foreach ($items 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($items, fn($x) => API::satisfiesCondition($x))) {
> 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().
>
> Previous discussion was in
> https://externals.io/message/103357#103373
>
> - New contributors to projects wouldn't know about any() and all() if it
> was reimplemented with different semantics and only occasionally used
> (e.g. MyArrayUtil::any()) in various projects)
> - If this was provided only in userland, there'd be low adoption and code
> such as the first example would remain common.
> If the standard library provided it, then polyfills would as well,
> making cleaner code easier to write.
>
> Thanks,
> - Tyson
>
Would it make sense, instead of having a third boolean parameter (causing
two parameters to be coupled together - already quite messy with existing
array functions) for
any() and all() to just detect if the given
callback requires >1 parameter?
That would make this much simpler.
Marco Pivetta
http://twitter.com/Ocramius
http://ocramius.github.com/