From ab5d1c699755f51192d5cab00bf0e601032018b3 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Mon, 22 Nov 2021 06:08:52 +0000 Subject: (list)+filter function This generates a new list, and appends to it every time the current list value satisfies the condition. It then recursively calls the filter on the next value. --- list.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/list.cpp b/list.cpp index b83b018..caa4fbc 100644 --- a/list.cpp +++ b/list.cpp @@ -75,6 +75,16 @@ T reduce(List *lst, T (*reducer) (T, T), T init = 0) return reduce(lst->next, reducer, init); } +template +List *filter(List *lst, bool (*f)(T), List *new_lst = nullptr) +{ + if (!lst) + return new_lst; + if (f(lst->value)) + new_lst = append(new_lst, lst->value); + return filter(lst->next, f, new_lst); +} + template std::ostream& operator<<(std::ostream& ostream, const List *lst) { -- cgit v1.2.3-13-gbd6f