Skip to content

Reduction

reduce(function: Binary[T, T, T], iterable: Iterable[T]) -> T

Reduces the given iterable using the function.

Example
from operator import add

from funcs.reduction import reduce

print(reduce(add, [1, 2, 3, 4, 5]))  # 15

Parameters:

Name Type Description Default
function Binary[T, T, T]

The function to use in reduction.

required
iterable Iterable[T]

The iterable to reduce.

required

Returns:

Type Description
T

The reduced value.

Source code in src/funcs/reduction.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def reduce(function: Binary[T, T, T], iterable: Iterable[T]) -> T:
    """Reduces the given `iterable` using the `function`.

    Example:
        ```python
        from operator import add

        from funcs.reduction import reduce

        print(reduce(add, [1, 2, 3, 4, 5]))  # 15
        ```

    Arguments:
        function: The function to use in reduction.
        iterable: The iterable to reduce.

    Returns:
        The reduced value.
    """
    return standard_reduce(function, iterable)

fold(initial: U, function: Binary[U, T, U], iterable: Iterable[T]) -> U

Folds the given iterable using the function and the initial value.

Parameters:

Name Type Description Default
initial U

The initial value to use in folding.

required
function Binary[U, T, U]

The function to use in folding.

required
iterable Iterable[T]

The iterable to fold.

required

Returns:

Type Description
U

The folded value.

Source code in src/funcs/reduction.py
36
37
38
39
40
41
42
43
44
45
46
47
def fold(initial: U, function: Binary[U, T, U], iterable: Iterable[T]) -> U:
    """Folds the given `iterable` using the `function` and the `initial` value.

    Arguments:
        initial: The initial value to use in folding.
        function: The function to use in folding.
        iterable: The iterable to fold.

    Returns:
        The folded value.
    """
    return standard_reduce(function, iterable, initial)