From e526414c759ebca82f1071cdeafe1160bcaa9637 Mon Sep 17 00:00:00 2001 From: Ebrahim Byagowi Date: Sun, 31 Mar 2019 12:41:58 +0430 Subject: [PATCH] [iter] Implement hb_reduce --- src/hb-iter.hh | 28 ++++++++++++++++++++++++++++ src/test-iter.cc | 5 +++++ 2 files changed, 33 insertions(+) diff --git a/src/hb-iter.hh b/src/hb-iter.hh index b212aa303..04261bd2d 100644 --- a/src/hb-iter.hh +++ b/src/hb-iter.hh @@ -348,6 +348,34 @@ static const struct { return hb_filter_iter_factory_t (p, f); } } hb_filter HB_UNUSED; +template +struct hb_reduce_t +{ + hb_reduce_t (Redu r, TValue init_value) : r (r), init_value (init_value) {} + + template + TValue + operator () (Iter it) const + { + TValue value = init_value; + for (; it; ++it) + value = r (*it, value); + return value; + } + + private: + Redu r; + TValue init_value; +}; +static const struct +{ + template hb_reduce_t + operator () (Redu&& r, TValue init_value) const + { return hb_reduce_t (r, init_value); } +} hb_reduce HB_UNUSED; + + /* hb_zip() */ template diff --git a/src/test-iter.cc b/src/test-iter.cc index 205fd33c2..e142c560a 100644 --- a/src/test-iter.cc +++ b/src/test-iter.cc @@ -154,6 +154,11 @@ main (int argc, char **argv) | hb_apply (&st) ; + + hb_iter (src) + | hb_map ([&] (int i) -> int { return 1; }) + | hb_reduce ([&] (int acc, int cur) -> int { return acc + cur; }, 2) + ; + + hb_iter (src) | hb_drain ;