Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-04-15 06:25:27


From: "Aleksey Gurtovoy" <agurtovoy_at_[hidden]>
> > A fold/reduce version of count_if can indeed be easy to understand [1]
> given
> > the right background, but the version I presented is a simple rewrite of
> the
> > STL count_if. When in Rome...
>
> ".. do as the Romans"? Well, I don't think that _your_ version falls under
> that criteria. You've replaced an iteration primitive (something like
> 'while' statement) by "manual" recursion, while MPL 'fold'-based
> implementation replaces it by another, more high-level library-provided
> iteration primitive. It's at least arguable which one is close to the
> "original".

I have replaced the natural procedural iteration primitive (loop) with the
natural pure iteration primitive (tail recursion.) And I accept iterator
ranges.

> > [1] count_if(v, p) :- fold(v, lambda(x, n)(p(x)? n+1: n), 0).
> >
> > Your rendition of the above was too hard for me to grok, though.
>
> Is this one better?
>
> template<
> typename Sequence
> , typename Predicate
> >
> struct count_if
> {
> typedef typename fold<
> Sequence
> , integral_c<unsigned long, 0>
> , select_if< apply<Predicate,_2>, next<_1>, _1 >
> >::type type;
> };

Much better, thank you. It's only the comments that are missing.

template<class S, class P> struct count_if
{
    typedef select_if< apply<P, _2>, next<_1>, _1 > F; // lambda(x, n) p(x)?
n+1: n
    typedef integral_c<long, 0> zero;
    typedef typename fold<S, zero, F>::type type;
};


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk