1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 11:37:44 +00:00

AK: Reimplement all_of in terms of find_if

Problem:
- Now that a generic free-function form of `find_if` is implemented
  the code in `all_of` is redundant.

Solution:
- Follow the "don't repeat yourself" mantra and make the code DRY by
  implementing `all_of` in terms of `find_if`.
- One tricky part is that since captures are not permitted in
  `constexpr` lambdas, the lambda created to negate the predicate
  needs to be created by a function which does not capture and takes
  the predicate at run-time instead. This allows `all_of` to continue
  to work in a `constexpr` context.
This commit is contained in:
Lenny Maiorani 2021-06-24 10:24:13 -06:00 committed by Ali Mohammad Pur
parent 497a9afaaf
commit 2cf4781d14

View file

@ -7,6 +7,7 @@
#pragma once #pragma once
#include <AK/Concepts.h> #include <AK/Concepts.h>
#include <AK/Find.h>
#include <AK/Iterator.h> #include <AK/Iterator.h>
namespace AK { namespace AK {
@ -17,22 +18,16 @@ constexpr bool all_of(
TEndIterator const& end, TEndIterator const& end,
auto const& predicate) auto const& predicate)
{ {
for (auto iter = begin; iter != end; ++iter) { constexpr auto negated_predicate = [](auto const& pred) {
if (!predicate(*iter)) { return [&](auto const& elem) { return !pred(elem); };
return false; };
} return !(find_if(begin, end, negated_predicate(predicate)) != end);
}
return true;
} }
template<IterableContainer Container> template<IterableContainer Container>
constexpr bool all_of(Container&& container, auto const& predicate) constexpr bool all_of(Container&& container, auto const& predicate)
{ {
for (auto&& entry : container) { return all_of(container.begin(), container.end(), predicate);
if (!predicate(entry))
return false;
}
return true;
} }
} }