Boost logo

Boost :

Subject: Re: [boost] [Hana] Informal review request
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2015-03-17 15:15:30


On 03/17/2015 11:39 AM, Louis Dionne wrote:
> <snip>
> template <typename Sequence, typename State, typename F>
> auto foldr(Sequence xs, State s, F f) {
> if (is_empty(xs))
> return s;
> else
> return f(head(xs), foldr(tail(xs), s, f));
> }
> <snip>
> since `f` never uses the value of its second argument, this argument
> is never evaluated. So the "else" branch inside the `foldr` becomes:
> return f(thunk[head(xs)], thunk[foldr(tail(xs), s, f)]);
> --> return head(xs);
> and the recursive call to `foldr` is never evaluated. This allows
> processing infinite lists lazily and writing short-circuiting algorithms
> such as
> template <typename Sequence, typename Predicate>
> bool any_of(Sequence xs, Predicate pred) {
> return foldr(xs, false, [](auto x, auto y) {
> return pred(x) || pred(y);
> });
> }

I know this looks cool, but it's actually a perfect
example of why foldr on an infinite sequence isn't
a good idea. On an infinite sequence, this any_of
will either return true or will go into infinite
recursion. I can't see any practical use for such
behavior. If I ever needed to use any_of on an
infinite sequence, I doubt that having the false
case fail would be acceptable. An any_of that
actually handles the false case for infinite sequences
can't be implemented generically. IMHO, foldr
makes it much too easy to write algorithms like
this that almost work.

In Christ,
Steven Watanabe

Boost list run by bdawes at, gregod at, cpdaniel at, john at