Python | Analogue |
---|---|
functools.reduce | foldl |
itertools.product | |
Indexing | fst and snd |
functool.partial | Partial function application |
itertools.accumulate | scanl |
filter / itertools.compress | filter |
General
- itertools.compress(l): make an iterator from a list ??
- itertools.cycle: Make infinite lists
- itertools.tee(it, n): Duplicate an iterator n times
- functools.lrucache: memoize a function
- The argument function better be pure
See:
functools.reduce
- Kind of like
foldl
where first element is taken as accumulator. - Error if iterable is empty.
Using example from docs:
>>> import functools as f
>>> f.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
15
# ((((1+2)+3)+4)+5)
>>> f.reduce(lambda x, y: x+y, [4, 5])
9
>>> f.reduce(lambda x, y: x+y, [4])
4
>>> f.reduce(lambda x, y: x+y, [])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: reduce() of empty sequence with no initial value
itertools.product
>>> import itertools
>>> a=[1, 2, 3]
>>> b=[2, 3]
>>> [(i,j) for (i,j) in itertools.product(a,b)]
[(1, 2), (1, 3), (2, 2), (2, 3), (3, 2), (3, 3)]
Tuples: fst and snd
>>> a=(3,2)
>>> a[0]
3
>>> a[1]
2
>>> a[1:]
(2,)
Misc
- coconut: A Python-like language with features to support functional programming style
- https://github.com/sfermigier/awesome-functional-python
- https://old.reddit.com/r/functional_python/