Skip to content

Instantly share code, notes, and snippets.

@mithereal
Created January 3, 2018 17:06
Show Gist options
  • Save mithereal/186777574b0bde02e363da6af9606ae0 to your computer and use it in GitHub Desktop.
Save mithereal/186777574b0bde02e363da6af9606ae0 to your computer and use it in GitHub Desktop.
elixir filter from a list
defmodule Filter do
@moduledoc """
this module will filter out results from a list via body or tail recursion
"""
@doc """
this will filter one result from the list via tail recursion
"""
def reject_one([head | tail], fun) do
if fun.(head), do: tail, else: reject_one(tail, fun, [head])
end
def reject_one([head | tail], fun, acc) do
if fun.(head), do: acc ++ tail, else: reject_one(tail, fun, [head | acc])
end
@doc """
this will filter one result from the list via body recursion
"""
def br_reject_one([], _fun), do: []
def br_reject_one([head | tail], fun) do
if fun.(head) do
tail
else
[head | br_reject_one(tail, fun)]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment