From b8ade145405ee0c9b9319108a6ef05bc17e3dc83 Mon Sep 17 00:00:00 2001 From: Patrick Pelissier Date: Thu, 23 Feb 2017 23:07:52 +0100 Subject: [PATCH] Add ALGO_EXTRACT --- m-algo.h | 30 ++++++++++++++++++++++++++++-- tests/test-malgo.c | 19 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/m-algo.h b/m-algo.h index f910fd3b..6e8a349f 100644 --- a/m-algo.h +++ b/m-algo.h @@ -39,7 +39,12 @@ #define ALGO_MAP(container, cont_oplist, ...) \ M_IF_NARGS_EQ1(__VA_ARGS__) \ (ALGOI_MAP(container, cont_oplist, __VA_ARGS__), \ - ALGOI_MAP_ARG(name, cont_oplist, __VA_ARGS__ )) + ALGOI_MAP_ARG(container, cont_oplist, __VA_ARGS__ )) + +#define ALGO_EXTRACT(contD, contDop, contS, contSop, ...) \ + M_IF_NARGS_EQ1(__VA_ARGS__) \ + (ALGOI_EXTRACT(contD, contDop, contS, contSop, __VA_ARGS__), \ + ALGOI_EXTRACT_ARG(contD, contDop, contS, contSop, __VA_ARGS__ )) /********************************** INTERNAL ************************************/ @@ -203,7 +208,6 @@ //TODO: const_iterator & CM_EACH missing... //TODO: Algorithm missing // nth_element, reduce, find_last, find_if, count_if, ... -//TODO: Copy from a container to another if condition. #define ALGOI_MAP(container, cont_oplist, func) \ for M_EACH(item, l, cont_oplist) { \ @@ -215,4 +219,26 @@ func(__VA_ARGS__, *item); \ } \ +#define ALGOI_EXTRACT(contDst, contDstOplist, \ + contSrc, contSrcOplist, \ + condFunc) do { \ + M_GET_CLEAN contDstOplist (contDst); \ + for M_EACH(item, contSrc, contSrcOplist) { \ + if (condFunc (*item)) \ + M_GET_PUSH contDstOplist (contDst, *item); \ + } \ + M_IF_METHOD(REVERSE, contDstOplist) (M_GET_REVERSE contDstOplist (contDstOplist);, ) \ + } while (0) + +#define ALGOI_EXTRACT_ARG(contDst, contDstOplist, \ + contSrc, contSrcOplist, \ + condFunc, ...) do { \ + M_GET_CLEAN contDstOplist (contDst); \ + for M_EACH(item, contSrc, contSrcOplist) { \ + if (condFunc (__VA_ARGS__, *item)) \ + M_GET_PUSH contDstOplist (contDst, *item); \ + } \ + M_IF_METHOD(REVERSE, contDstOplist) (M_GET_REVERSE contDstOplist (contDstOplist);, ) \ + } while (0) + #endif diff --git a/tests/test-malgo.c b/tests/test-malgo.c index 105435d4..2d89e3c4 100644 --- a/tests/test-malgo.c +++ b/tests/test-malgo.c @@ -73,10 +73,29 @@ static void test_string(void) list_string_clear(l); } +static void test_extract(void) +{ + list_int_t l; + list_int_init (l); + for(int i = -100; i < 100; i++) + list_int_push_back (l, i); + array_int_t a; + array_int_init(a); +#define cond(d) ((d) > 0) + ALGO_EXTRACT(a, ARRAY_OPLIST(int), l, LIST_OPLIST(int), cond); + assert(array_int_size(a) == 99); +#define cond2(c, d) ((d) > (c)) + ALGO_EXTRACT(a, ARRAY_OPLIST(int), l, LIST_OPLIST(int), cond2, 10); + assert(array_int_size(a) == 89); + array_int_clear(a); + list_int_clear(l); +} + int main(void) { test_list(); test_array(); test_string(); + test_extract(); exit(0); }