@@ -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