|
| 1 | +import functools |
1 | 2 | from toolz.itertoolz import partition_all |
2 | 3 | from toolz.compatibility import reduce, map |
3 | 4 | from toolz.utils import no_default |
4 | 5 |
|
5 | 6 |
|
| 7 | +def _reduce(func, seq, initial=None): |
| 8 | + if initial is None: |
| 9 | + return functools.reduce(func, seq) |
| 10 | + else: |
| 11 | + return functools.reduce(func, seq, initial) |
| 12 | + |
| 13 | + |
6 | 14 | def fold(binop, seq, default=no_default, map=map, chunksize=128, combine=None): |
7 | 15 | """ |
8 | 16 | Reduce without guarantee of ordered reduction. |
@@ -43,16 +51,22 @@ def fold(binop, seq, default=no_default, map=map, chunksize=128, combine=None): |
43 | 51 | >>> fold(add, [1, 2, 3, 4], chunksize=2, map=map) |
44 | 52 | 10 |
45 | 53 | """ |
| 54 | + assert chunksize > 1 |
| 55 | + |
46 | 56 | if combine is None: |
47 | 57 | combine = binop |
48 | 58 |
|
49 | 59 | chunks = partition_all(chunksize, seq) |
50 | 60 |
|
51 | 61 | # Evaluate sequence in chunks via map |
52 | 62 | if default == no_default: |
53 | | - results = map(lambda chunk: reduce(binop, chunk), chunks) |
| 63 | + results = map( |
| 64 | + functools.partial(_reduce, binop), |
| 65 | + chunks) |
54 | 66 | else: |
55 | | - results = map(lambda chunk: reduce(binop, chunk, default), chunks) |
| 67 | + results = map( |
| 68 | + functools.partial(_reduce, binop, initial=default), |
| 69 | + chunks) |
56 | 70 |
|
57 | 71 | results = list(results) # TODO: Support complete laziness |
58 | 72 |
|
|
0 commit comments