Code Haiku: Filter Items From an Elixir Map

RecursiveEnigma
TechDev Mix
Published in
1 min readSep 5, 2015

--

In Elixir, to filter items with nil values from a Map collection using Enum.Reduce:

Enum.reduce %{ :result => "ok", :description => nil, :val => "haiku" }, %{}, fn { k, v }, acc ->
if v do
Map.put(acc, k, v)
else
acc
end
end

Reduce emits the result of the previous function as an accumulator, acc. An empty Map collection is used as the accumulator’s initial value, %{}. The last argument of reduce is an anonymous function with two arguments (it can also be written as fn ({ k, v }, acc) -> …), of which we pattern match the first one, the current item, into its constituent key and value. If the current item’s value isn’t null, we add the item to the accumulator collection using Map.put, otherwise we just return the accumulator.

--

--