AMDG On 03/17/2015 11:39 AM, Louis Dionne wrote:
<snip>
template
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
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