Exemplo n.º 1
0
def test_fold():
    """Testing fold module."""
    xs = list(range(10_000))
    ys = list(range(10_000))

    assert foldr(lambda x, y: x + y, 0, xs) == sum(xs)
    assert foldr(lambda x, y: x + y, 0, ys) == sum(ys)
    assert foldr(lambda _, y: y + 1, 0, xs) == len(xs)
    assert foldr(lambda _, y: y + 1, 0, ys) == len(ys)

    assert foldl(lambda x, y: x + y, 0, xs) == sum(xs)
    assert foldl(lambda x, y: x + y, 0, ys) == sum(ys)
    assert foldl(lambda x, _: x + 1, 0, xs) == len(xs)
    assert foldl(lambda x, _: x + 1, 0, ys) == len(ys)
Exemplo n.º 2
0
def concat(seq: Sequence[Sequence[Any]]) -> Sequence[Any]:
    """Implementation of concat in Python3.

    concat accepts a sequence of sequences and concatenates them.
    See the examples below.

    >>> concat([[1, 2, 3], [4, 5, 6]])
    [1, 2, 3, 4, 5, 6]
    >>> concat([["This", "is", "the"], ["concat", "function", "."]])
    ['This', 'is', 'the', 'concat', 'function', '.']
    """
    return list(foldr(lambda x, y: chain(x, y), [], seq))
Exemplo n.º 3
0
def any(fun: Callable[[Any], bool], seq: Sequence[Any]) -> bool:
    """Implementation of any in Python3.

    This is an implementation of any function
    from functional programming. See examples
    below.

    >>> foldl((lambda x, _: x + 1), 0, [0, 1, 2, 3, 4])
    5
    >>> foldl((lambda x, y: x + y), 0, [0, 1, 2, 3, 4])
    10
    """
    return foldr((lambda x, y: x or y), False, list(map(fun, seq)))
Exemplo n.º 4
0
def concat_map(
    fun: Callable[[Any], Sequence[Any]], seq: Sequence[Any]
) -> Sequence[Any]:
    """Implementation of concat_map in Python3.

    concat_map creates a sequence from a sequence generating function by
    application of this function on all elements in a sequence passed
    as the second argument. See the examples below.

    >>> concat_map(lambda x: [x + 1], [1, 2, 3])
    [2, 3, 4]
    >>> concat_map(lambda x: [x + " "], ["a", "b", "c"])
    ['a ', 'b ', 'c ']
    """
    return list(foldr(lambda x, y: chain(fun(x), y), [], seq))