Skip to content

Commit 907149c

Browse files
author
José Valim
committed
Improve docs for Enum.filter/2
1 parent c99e1cd commit 907149c

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

lib/elixir/lib/enum.ex

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -832,13 +832,28 @@ defmodule Enum do
832832
Filters the enumerable, i.e. returns only those elements
833833
for which `fun` returns a truthy value.
834834
835-
See also `reject/2`.
835+
See also `reject/2` which discards all elements where the
836+
function returns true.
836837
837838
## Examples
838839
839840
iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)
840841
[2]
841842
843+
Keep in mind that `filter` is not capable of filtering and
844+
transforming an element at the same time. If you would like
845+
to do so, consider using `flat_map/2`. For example, if you
846+
want to convert all strings that represent an integer and
847+
discard the invalid one in one pass:
848+
849+
strings = ["1234", "abc", "12ab"]
850+
Enum.flat_map(strings, fn string ->
851+
case Integer.parse(string) do
852+
{int, _rest} -> [int] # transform to integer
853+
:error -> [] # skip the value
854+
end
855+
end)
856+
842857
"""
843858
@spec filter(t, (element -> as_boolean(term))) :: list
844859
def filter(enumerable, fun) when is_list(enumerable) do

0 commit comments

Comments
 (0)