From 1be7896f19c2633f247a11dc486189a18d2be388 Mon Sep 17 00:00:00 2001 From: Nathan Mattes Date: Tue, 14 Sep 2021 16:53:26 +0200 Subject: [PATCH] Implement filter I struggled a bit on this one, it took me two months!!!! jk My assumption was that filter with an empty list does nothing, but actually, it returns an empty list. Second misunderstanding was that filter with tail doesn't need to be wrapped into another list. But hey, in the end I learned something! --- maps/myenum.exs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/maps/myenum.exs b/maps/myenum.exs index 97f6405..2cbd775 100644 --- a/maps/myenum.exs +++ b/maps/myenum.exs @@ -30,7 +30,21 @@ defmodule MyEnum do :ok end + # Filters the enumerable, i.e. returns only those elements for which fun returns a truthy value. + def filter([], _fun) do + # do nothing -> This is wrong. Return an empty array instead. + [] + end + # filter using if ... do ... else ... end + def filter([head|tail], fun) do + if fun.(head) do + [head|filter(tail, fun)] + else + filter(tail, fun) + end + end + # split # take end