xotl.tools.fp.iterators – High-level functional tools for iterators

Functional tools for functions that returns iterators (generators, etc.)

Warning

This module is experimental. It may be removed completely, moved or otherwise changed.

xotl.tools.fp.iterators.kleisli_compose(*fs) → Callable[[T], Iterable[T]][source]

The Kleisli composition operator (right-to-left version).

For two functions, kleisli_compose(g, f) returns:

lambda x: (z for y in f(x) for z in g(y))

In general this is, reduce(_compose, fs, lambda x: [x]); where _compose is the lambda for two arguments.

Note

Despite name (Kleisli), Python does not have a true Monad type-class. So this function works with functions taking a single argument and returning an iterator – it also works with iterables.

New in version 1.9.6.

Changed in version 1.9.7: Name changed to kleisli_compose.

Warning

You may want to use kleisli_compose_foldl() which matches the order semantics of the functional kleisli composition >=>.

xotl.tools.fp.iterators.kleisli_compose_foldl(*fs) → Callable[[T], Iterable[T]][source]

Same as kleisli_compose() but composes left-to-right.

Examples:

>>> s15 = lambda s: tuple(s + str(i) for i in range(1, 5))
>>> s68 = lambda s: tuple(s + str(i) for i in range(6, 8))
>>> # kleisli_compose produces "6" >>= 1, 2, 3, 4; and then "7" >>= 1, 2, 3, 4
>>> list(kleisli_compose(s15, s68)(""))
['61', '62', '63', '64', '71', '72', '73', '74']
>>> list(kleisli_compose_foldl(s15, s68)(""))
['16', '17', '26', '27', '36', '37', '46', '47']

If the operation is non-commutative (as the string concatenation) you end up with very different results.

>>> n15 = lambda s: tuple(s + i for i in range(1, 5))
>>> n68 = lambda s: tuple(s + i for i in range(6, 8))
>>> list(kleisli_compose(n15, n68)(0))
[7, 8, 9, 10, 8, 9, 10, 11]
>>> list(kleisli_compose_foldl(n15, n68)(0))
[7, 8, 8, 9, 9, 10, 10, 11]

If the operation is commutative you get the same set of results, but the order may be different.

xotl.tools.fp.iterators.iter_compose()

Deprecated since version 1.9.7: Alias of xotl.tools.fp.iterators.kleisli_compose()