Skip to content

Commit 474250e

Browse files
committed
Update docs for Enum.Iterator and reduce
1 parent a1ec5f1 commit 474250e

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

lib/elixir/lib/enum.ex

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,38 @@ defprotocol Enum.Iterator do
44
55
Usually, when you invoke a function in the module `Enum`, the first argument
66
passed to it is a collection which is forwarded to this protocol in order to
7-
retrieve information on how to iterate the collection.
7+
perform operations on the collection.
88
99
For example, in the expression
1010
1111
Enum.map([1,2,3], &1 * 2)
1212
13-
`Enum.map` invokes `Enum.Iterator.iterator([1,2,3])` to retrieve the iterator
14-
function that will drive the iteration process.
13+
`Enum.map` invokes `Enum.Iterator.reduce` to perform the reducing operation
14+
that builds a mapped list by calling the mapping function `&1 * 2` on every
15+
element in the collection and cons'ing the element with the accumulated list.
1516
"""
1617

1718
@only [List, Record, Function]
1819

20+
@doc """
21+
This function performs the reducing operation on a given collection. It
22+
returns the accumulated value of applying the given function `fun` on every
23+
element with the accumulated value.
24+
25+
As an example, here is the implementation of `reduce` for lists:
26+
27+
def reduce([h|t], acc, fun), do: reduce(t, fun.(h, acc), fun)
28+
def reduce([], acc, _fun), do: acc
29+
30+
As an additional example, here is the implementation of `Enum.map` with
31+
`Enum.Iterator`:
32+
33+
def map(collection, fun) do
34+
Enum.Iterator.reduce(collection, [], fn(entry, acc) ->
35+
[fun.(entry)|acc]
36+
end) |> :lists.reverse
37+
end
38+
"""
1939
def reduce(collection, acc, fun)
2040

2141
@doc """

0 commit comments

Comments
 (0)