exercism-elixir/strain/lib/strain.ex
2022-02-13 11:06:04 -04:00

27 lines
675 B
Elixir

defmodule Strain do
@doc """
Given a `list` of items and a function `fun`, return the list of items where
`fun` returns true.
Do not use `Enum.filter`.
"""
@spec keep(list :: list(any), fun :: (any -> boolean)) :: list(any)
def keep([], _), do: []
def keep([h | tail], fun) do
if fun.(h) == true do
[h | keep(tail, fun)]
else
keep(tail, fun)
end
end
@doc """
Given a `list` of items and a function `fun`, return the list of items where
`fun` returns false.
Do not use `Enum.reject`.
"""
@spec discard(list :: list(any), fun :: (any -> boolean)) :: list(any)
def discard(list, fun), do: keep(list, &(!fun.(&1)))
end