summaryrefslogtreecommitdiff
path: root/Data/BuiltIn/Libraries/luafun/doc/transformations.rst
blob: e446d2f4c67db2eac616cd5f98cd119126d4f93a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
Transformations
===============

.. module:: fun

.. function:: map(fun, gen, param, state)
              iterator:map(fun)

   :param fun: a function to apply
   :type  fun: (function(...) -> ...)
   :returns: a new iterator

   Return a new iterator by applying the **fun** to each element of
   ``gen, param, state`` iterator. The mapping is performed on the fly
   and no values are buffered.

   Examples:

   .. code-block:: lua

    > each(print, map(function(x) return 2 * x end, range(4)))
    2
    4
    6
    8

    fun = function(...) return 'map', ... end
    > each(print, map(fun, range(4)))
    map 1
    map 2
    map 3
    map 4

.. function:: enumerate(gen, param, state)
              iterator:enumerate()

   :returns: a new iterator

   Return a new iterator by enumerating all elements of the
   ``gen, param, state`` iterator starting from ``1``. The mapping is performed
   on the fly and no values are buffered.

   Examples:

   .. code-block:: lua

    > each(print, enumerate({"a", "b", "c", "d", "e"}))
    1 a
    2 b
    3 c
    4 d
    5 e

    > each(print, enumerate(zip({"one", "two", "three", "four", "five"},
        {"a", "b", "c", "d", "e"})))
    1 one a
    2 two b
    3 three c
    4 four d
    5 five e

.. function:: intersperse(x, gen, param, state)
              iterator:intersperse(x)

   :type x: any
   :returns: a new iterator

   Return a new iterator where the **x** value is interspersed between the
   elements of the source iterator. The **x** value can also be added as a
   last element of returning iterator if the source iterator contains the odd
   number of elements.

   Examples:

   .. code-block:: lua

    > each(print, intersperse("x", {"a", "b", "c", "d", "e"}))
    a
    x
    b
    x
    c
    x
    d
    x
    e
    x