On Tue, Jan 30, 2018 at 11:13 AM, Larry Garfield <la...@garfieldtech.com> wrote:
> On Monday, January 29, 2018 6:46:10 PM CST Michael Morris wrote:
>> On Mon, Jan 29, 2018 at 6:16 PM, Larry Garfield <la...@garfieldtech.com>
>>
>> wrote:
>> > Really, these functions would be useful only on arrays, period.  To allow
>> > them
>> > on anything else is just dangerous, and on other iterables there are
>> > better,
>> > more robust approaches (as discussed elsewhere in this thread).
>> >
>> > As you've demonstrated they're also quite compact and effective to do in
>> > user-
>> > space, so unless there's a massive performance difference of moving them
>> > to C
>> > they don't seem all that appropriate to add to the language directly.
>> >
>> > --Larry Garfield
>>
>> Didn't you personally raise the issue of hard dependencies doing this sort
>> of functionality creates? Implementable in userland or not, this is pretty
>> low level functionality.
>
> I don't recall doing so in this thread, but I most likely have on some other
> issue.  It's the sort of comment that I would make. :-)
>
> However, that's for a very commonly used function where just inlining it is
> prohibitive.  As you've demonstrated below, this functionality is easily a one
> liner, and it's a one-liner in an assert statement most likely.
>
>> Hmm..  If limited to arrays only then array_filter with count is pretty
>> close to what we want.
>>
>> assert(count(array_filter($a, is_string)) === count($a));
>>
>> That's not optimal though - granted assert code doesn't *have* to be
>> optimal, but that's still a wordy construction.
>
> Personally I think that's fine, and doesn't need a language-level utility
> function to wrap it any further.
>
> (Yes, that's a subjective metric.  So are most statements about what
> should[n't] be included in the language itself.  Others are welcome to
> disagree, but this falls below my threshold of necessity.)
>
> --Larry Garfield


I agree with this sentiment from Larry. However I do think there is a
function we could add:

    function every(callable $predicate, traversable $input): bool {
        foreach ($input as $value) {
            if (!$predicate($value)) {
                return false;
            }
        }
        return true;
    }

In which case the code would become:

    assert(every('is_string', $input));

Of course, when passing a traversable the caller must to be careful as
it will be consumed. If they don't want that to happen they can
convert it to an array (possibly with iterator_to_array).

The reason this "every" function is better than "array_test" is
because it is more general and works with more things than just types.
The name "every" I borrowed from Clojure, but it's known by many
names; in Java it is known as "allMatch".

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to