@@ -4,18 +4,38 @@ defprotocol Enum.Iterator do
4
4
5
5
Usually, when you invoke a function in the module `Enum`, the first argument
6
6
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.
8
8
9
9
For example, in the expression
10
10
11
11
Enum.map([1,2,3], &1 * 2)
12
12
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.
15
16
"""
16
17
17
18
@ only [ List , Record , Function ]
18
19
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
+ """
19
39
def reduce ( collection , acc , fun )
20
40
21
41
@ doc """
0 commit comments