Skip to content

Commit

Permalink
Add visibility for flat_map filtering in docs (#13794)
Browse files Browse the repository at this point in the history
  • Loading branch information
sabiwara authored Aug 26, 2024
1 parent a564c2e commit 1889ee9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/elixir/lib/enum.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions lib/elixir/pages/cheatsheets/enum-cheat.cheatmd
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 1889ee9

Please sign in to comment.