Combining predicates in a functional way

扶醉桌前 提交于 2021-02-10 17:53:14

问题


Does Boost Hana provide a way to combine predicates with logical operators?

I'm referring to something roughly like this

constexpr auto both = [](auto&& f, auto&& g){
    return [&f,&g](auto&& x){ return f(x) && g(x); };
};

that could be used like this:

int main() {
    std::vector<int> v{1,2,3,4,5,6,7,8,9,10};
    auto less_than_7 = hana::reverse_partial(std::less_equal<int>{}, 7);
    auto more_than_3 = hana::reverse_partial(std::greater_equal<int>{}, 3);
    auto r = ranges::views::remove_if(v, both(less_than_7, more_than_3));
}

where, from Hana, I'd expect also a way to use it in an infix way similar to hana::on, as in both(less_than_7, more_than_3) === less_than_7 ^both^ more_than_3 (even though and would be nicer, but I've just found that it's a synonym for &&).

Or maybe does it offer a way to lift the standard operator && to operate on function functors?


回答1:


You could use demux like:

auto both = hana::demux(std::logical_and<bool>{});
// Or for any number of predicates
auto all = hana::demux([](auto const&... x) noexcept(noexcept((static_cast<bool>(x), ...))) { return (true && ... && static_cast<bool>(x)); });
ranges::views::remove_if(v, both(less_than_7, more_than_3));


来源:https://stackoverflow.com/questions/64259413/combining-predicates-in-a-functional-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!