diff --git a/lib/elixir/lib/enum.ex b/lib/elixir/lib/enum.ex index d92ab519648..187e403d2b4 100644 --- a/lib/elixir/lib/enum.ex +++ b/lib/elixir/lib/enum.ex @@ -1257,6 +1257,14 @@ defmodule Enum do iex> Enum.flat_map([:a, :b, :c], fn x -> [[x]] end) [[:a], [:b], [:c]] + This is frequently used to to transform and filter in one pass, returning empty + lists to exclude results: + + iex> Enum.flat_map([4, 0, 2, 0], fn x -> + ...> if x != 0, do: [1 / x], else: [] + ...> end) + [0.25, 0.5] + """ @spec flat_map(t, (element -> t)) :: list def flat_map(enumerable, fun) when is_list(enumerable) do diff --git a/lib/elixir/pages/cheatsheets/enum-cheat.cheatmd b/lib/elixir/pages/cheatsheets/enum-cheat.cheatmd index 35198aeee8f..500fce204e0 100644 --- a/lib/elixir/pages/cheatsheets/enum-cheat.cheatmd +++ b/lib/elixir/pages/cheatsheets/enum-cheat.cheatmd @@ -99,6 +99,19 @@ iex> Enum.reject(cart, &(&1.fruit =~ "o")) ] ``` +### [`flat_map(enum, fun)`](`Enum.flat_map/2`) + +This function (also listed [below](#concatenating-flattening)) can +be used to transform and filter in one pass, returning empty lists +to exclude results: + +```elixir +iex> Enum.flat_map(cart, fn item -> +...> if item.count > 1, do: [item.fruit], else: [] +...> end) +["apple", "orange"] +``` + ### [`Comprehension`](`for/1`) Filtering can also be done with comprehensions: