pythonic-fp.iterables 4.0.0__py3-none-any.whl → 5.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ # Copyright 2023-2024 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Library of functions for iterating iterables.
16
+
17
+ +-----------+-------------------------------------------+
18
+ | Module | Description |
19
+ +===========+===========================================+
20
+ | merging | Concatenating and merging iterables |
21
+ +-----------+-------------------------------------------+
22
+ | drop_take | Dropping and taking values from iterables |
23
+ +-----------+-------------------------------------------+
24
+ | folding | Reducing and accumulating iterables |
25
+ +-----------+-------------------------------------------+
26
+
27
+ Assumptions:
28
+
29
+ - iterables are not necessarily iterators
30
+ - at all times iterator protocol is assumed to be followed
31
+
32
+ - all iterators are assumed to be iterable
33
+ - for all iterators ``foobar`` we assume ``iter(foobar) is foobar``
34
+
35
+ """
36
+
37
+ __author__ = 'Geoffrey R. Scheller'
38
+ __copyright__ = 'Copyright (c) 2023-2025 Geoffrey R. Scheller'
39
+ __license__ = 'Apache License 2.0'
@@ -0,0 +1,177 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Module pythonic_fp.iterables.drop_take"""
16
+
17
+ from __future__ import annotations
18
+
19
+ __author__ = 'Geoffrey R. Scheller'
20
+ __copyright__ = 'Copyright (c) 2023-2025 Geoffrey R. Scheller'
21
+ __license__ = 'Apache License 2.0'
22
+
23
+ from collections.abc import Callable, Iterable, Iterator
24
+ from pythonic_fp.gadgets.box import Box
25
+ from .merging import concat
26
+
27
+ __all__ = [
28
+ 'drop',
29
+ 'drop_while',
30
+ 'take',
31
+ 'take_while',
32
+ 'take_split',
33
+ 'take_while_split',
34
+ ]
35
+
36
+
37
+ ## dropping and taking
38
+
39
+
40
+ def drop[D](iterable: Iterable[D], n: int) -> Iterator[D]:
41
+ """Drop the next n values from iterable.
42
+
43
+ :param iterable: iterable whose values are to be dropped
44
+ :param n: number of values to be dropped
45
+ :return: an iterator of the remaining values
46
+
47
+ """
48
+ iterator = iter(iterable)
49
+ for _ in range(n):
50
+ try:
51
+ next(iterator)
52
+ except StopIteration:
53
+ break
54
+ return iterator
55
+
56
+
57
+ def drop_while[D](
58
+ iterable: Iterable[D],
59
+ pred: Callable[[D], bool]
60
+ ) -> Iterator[D]:
61
+ """Drop initial values from iterable while predicate is true.
62
+
63
+ :param iterable: iterable whose values are to be dropped
64
+ :param pred: Boolean valued function, the "predicate"
65
+ :return: an iterator beginning where pred returned false
66
+
67
+ """
68
+ iterator = iter(iterable)
69
+ while True:
70
+ try:
71
+ value = next(iterator)
72
+ if not pred(value):
73
+ iterator = concat((value,), iterator)
74
+ break
75
+ except StopIteration:
76
+ break
77
+ return iterator
78
+
79
+
80
+ def take[D](iterable: Iterable[D], n: int) -> Iterator[D]:
81
+ """Return an iterator of up to n initial values of an iterable.
82
+
83
+ :param iterable: iterable providing the values to be taken
84
+ :param n: number of values to be dropped
85
+ :return: an iterator of up to n initial values from iterable
86
+
87
+ """
88
+ iterator = iter(iterable)
89
+ for _ in range(n):
90
+ try:
91
+ value = next(iterator)
92
+ yield value
93
+ except StopIteration:
94
+ break
95
+
96
+
97
+ def take_while[D](
98
+ iterable: Iterable[D],
99
+ pred: Callable[[D], bool]
100
+ ) -> Iterator[D]:
101
+ """Yield values from iterable while predicate is true.
102
+
103
+ .. warning::
104
+ Risk of value loss if iterable is multiple referenced iterator.
105
+
106
+ :param iterable: iterable providing the values to be taken
107
+ :param pred: Boolean valued function, the "predicate"
108
+ :return: an Iterator of of values from iterable until predicate false
109
+
110
+ """
111
+ iterator = iter(iterable)
112
+ while True:
113
+ try:
114
+ value = next(iterator)
115
+ if pred(value):
116
+ yield value
117
+ else:
118
+ break
119
+ except StopIteration:
120
+ break
121
+
122
+
123
+ def take_split[D](
124
+ iterable: Iterable[D],
125
+ n: int
126
+ ) -> tuple[Iterator[D], Iterator[D]]:
127
+ """Same as take except also return iterator of remaining values.
128
+
129
+ .. Warning::
130
+
131
+ **CONTRACT:** Do not access the second returned iterator until the
132
+ first one is exhausted.
133
+
134
+ :param iterable: iterable providing the values to be taken
135
+ :param n: maximum number of values to be taken
136
+ :return: an iterator of values taken and an iterator of remaining values
137
+
138
+ """
139
+ iterator = iter(iterable)
140
+ itn = take(iterator, n)
141
+
142
+ return itn, iterator
143
+
144
+
145
+ def take_while_split[D](
146
+ iterable: Iterable[D], pred: Callable[[D], bool]
147
+ ) -> tuple[Iterator[D], Iterator[D]]:
148
+ """Yield values from iterable while predicate is true.
149
+
150
+ .. Warning::
151
+
152
+ **CONTRACT:** Do not access the second returned iterator until
153
+ the first one is exhausted.
154
+
155
+ :param iterable: iterable providing the values to be taken
156
+ :param pred: Boolean valued function
157
+ :return: tuple containing an iterator of values taken and an iterator of remaining values
158
+
159
+ """
160
+ def _take_while(
161
+ iterator: Iterator[D], pred: Callable[[D], bool], val: Box[D]
162
+ ) -> Iterator[D]:
163
+ while True:
164
+ try:
165
+ val.put(next(iterator))
166
+ if pred(val.get()):
167
+ yield val.pop()
168
+ else:
169
+ break
170
+ except StopIteration:
171
+ break
172
+
173
+ iterator = iter(iterable)
174
+ value: Box[D] = Box()
175
+ it_pred = _take_while(iterator, pred, value)
176
+
177
+ return (it_pred, concat(value, iterator))
@@ -0,0 +1,294 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Module pythonic_fp.iterables.folding"""
16
+
17
+ from __future__ import annotations
18
+
19
+ __author__ = 'Geoffrey R. Scheller'
20
+ __copyright__ = 'Copyright (c) 2023-2025 Geoffrey R. Scheller'
21
+ __license__ = 'Apache License 2.0'
22
+
23
+ from collections.abc import Callable, Iterable, Iterator
24
+ from typing import cast, Never
25
+ from pythonic_fp.fptools.function import negate, swap
26
+ from pythonic_fp.fptools.maybe import MayBe
27
+ from pythonic_fp.singletons.novalue import NoValue
28
+ from .drop_take import drop_while, take_while_split
29
+
30
+ __all__ = [
31
+ 'accumulate',
32
+ 'reduce_left',
33
+ 'fold_left',
34
+ 'maybe_fold_left',
35
+ 'sc_reduce_left',
36
+ 'sc_reduce_right',
37
+ ]
38
+
39
+ def accumulate[D, L](
40
+ iterable: Iterable[D],
41
+ f: Callable[[L, D], L],
42
+ initial: L | NoValue = NoValue()
43
+ ) -> Iterator[L]:
44
+ """Returns an iterator of partial fold values.
45
+
46
+ A pure Python version of standard library's ``itertools.accumulate``
47
+
48
+ - function ``f`` does not default to addition (for typing flexibility)
49
+ - begins accumulation with an "optional" ``initial`` value
50
+
51
+ :param iterable: iterable to be folded
52
+ :param f: two parameter function, first parameter for accumulated value
53
+ :param initial: "optional" initial value to start fold
54
+ :return: an iterator of the intermediate fold values
55
+
56
+ """
57
+ it = iter(iterable)
58
+ try:
59
+ it0 = next(it)
60
+ except StopIteration:
61
+ if initial is NoValue():
62
+ return
63
+ yield cast(L, initial)
64
+ else:
65
+ if initial is not NoValue():
66
+ init = cast(L, initial)
67
+ yield init
68
+ acc = f(init, it0)
69
+ for ii in it:
70
+ yield acc
71
+ acc = f(acc, ii)
72
+ yield acc
73
+ else:
74
+ acc = cast(L, it0) # in this case L = D
75
+ for ii in it:
76
+ yield acc
77
+ acc = f(acc, ii)
78
+ yield acc
79
+
80
+
81
+ def reduce_left[D](
82
+ iterable: Iterable[D],
83
+ f: Callable[[D, D], D]
84
+ ) -> D | Never:
85
+ """Fold an iterable left with a function.
86
+
87
+ .. Warning::
88
+
89
+ This function never return if given an infinite iterable.
90
+
91
+ .. Warning::
92
+
93
+ This function does not catch or re-raises exceptions from ``f``.
94
+
95
+ :param iterable: iterable to be reduced (folded)
96
+ :param f: two parameter function, first parameter for accumulated value
97
+ :return: reduced value from the iterable
98
+ :raises StopIteration: when called on an empty iterable
99
+ :raises Exception: does not catch any exceptions from ``f``
100
+
101
+ """
102
+ it = iter(iterable)
103
+ try:
104
+ acc = next(it)
105
+ except StopIteration as exc:
106
+ msg = 'Attempt to reduce an empty iterable?'
107
+ raise StopIteration(msg) from exc
108
+
109
+ for v in it:
110
+ acc = f(acc, v)
111
+
112
+ return acc
113
+
114
+
115
+ def fold_left[D, L](
116
+ iterable: Iterable[D],
117
+ f: Callable[[L, D], L],
118
+ initial: L
119
+ ) -> L | Never:
120
+ """Fold an iterable left with a function and initial value.
121
+
122
+ - not restricted to ``__add__`` for the folding function
123
+ - initial value required, does not default to ``0`` for initial value
124
+ - handles non-numeric data just find
125
+
126
+ .. Warning::
127
+
128
+ This function never return if given an infinite iterable.
129
+
130
+ .. Warning::
131
+
132
+ This function does not catch any exceptions ``f`` may raise.
133
+
134
+ :param iterable: iterable to be folded
135
+ :param f: two parameter function, first parameter for accumulated value
136
+ :param initial: mandatory initial value to start fold
137
+ :return: the folded value
138
+
139
+ """
140
+ acc = initial
141
+ for v in iterable:
142
+ acc = f(acc, v)
143
+ return acc
144
+
145
+
146
+ def maybe_fold_left[D, L](
147
+ iterable: Iterable[D],
148
+ f: Callable[[L, D], L],
149
+ initial: L | NoValue = NoValue()
150
+ ) -> MayBe[L] | Never:
151
+ """Folds an iterable left with an "optional" initial value..
152
+
153
+ - when an initial value is not given then ``L = D``
154
+ - if iterable empty and no ``initial`` value given, return ``MayBe()``
155
+
156
+ .. Warning::
157
+
158
+ This function never return if given an infinite iterable.
159
+
160
+ .. Warning::
161
+
162
+ This function returns a ``MayBe()`` when ``f`` raises any
163
+ exception what-so-ever. The exception is thrown away.
164
+
165
+ :param iterable: The iterable to be folded.
166
+ :param f: First argument is for the accumulated value.
167
+ :param initial: Mandatory initial value to start fold.
168
+ :return: MayBe of a successfully folded value, otherwise MayBe()
169
+
170
+ """
171
+ acc: L
172
+ it = iter(iterable)
173
+ if initial is NoValue():
174
+ try:
175
+ acc = cast(L, next(it)) # in this case L = D
176
+ except StopIteration:
177
+ return MayBe()
178
+ else:
179
+ acc = cast(L, initial)
180
+
181
+ for v in it:
182
+ try:
183
+ acc = f(acc, v)
184
+ except Exception:
185
+ return MayBe()
186
+
187
+ return MayBe(acc)
188
+
189
+
190
+ def sc_reduce_left[D](
191
+ iterable: Iterable[D],
192
+ f: Callable[[D, D], D],
193
+ start: Callable[[D], bool] = (lambda d: True),
194
+ stop: Callable[[D], bool] = (lambda d: False),
195
+ include_start: bool = True,
196
+ include_stop: bool = True,
197
+ ) -> tuple[MayBe[D], Iterator[D]]:
198
+ """Short circuit version of a left reduce.
199
+
200
+ Useful for infinite iterables.
201
+
202
+ Behavior for default arguments will
203
+
204
+ - left reduce finite iterable
205
+ - start folding immediately
206
+ - continue folding until end (of a possibly infinite iterable)
207
+
208
+ :param iterable: iterable to be reduced from the left
209
+ :param f: two parameter function, first parameter for accumulated value
210
+ :param start: delay starting the fold until it returns true
211
+ :param stop: prematurely stop the fold when it returns true
212
+ :param include_start: if true, include fold starting value in fold
213
+ :param include_stop: if true, include stopping value in fold
214
+ :return: tuple of a MayBe of the folded value and iterator of remaining iterables
215
+
216
+ """
217
+ it_start = drop_while(iterable, negate(start))
218
+ if not include_start:
219
+ try:
220
+ next(it_start)
221
+ except StopIteration:
222
+ pass
223
+ it_reduce, it_rest = take_while_split(it_start, negate(stop))
224
+ mb_reduced = maybe_fold_left(it_reduce, f)
225
+ if include_stop:
226
+ if mb_reduced:
227
+ try:
228
+ last = next(it_rest)
229
+ mb_reduced = MayBe(f(mb_reduced.get(), last))
230
+ except StopIteration:
231
+ pass
232
+ else:
233
+ try:
234
+ last = next(it_rest)
235
+ mb_reduced = MayBe(last)
236
+ except StopIteration:
237
+ pass
238
+
239
+ return (mb_reduced, it_rest)
240
+
241
+
242
+ def sc_reduce_right[D](
243
+ iterable: Iterable[D],
244
+ f: Callable[[D, D], D],
245
+ start: Callable[[D], bool] = (lambda d: False),
246
+ stop: Callable[[D], bool] = (lambda d: False),
247
+ include_start: bool = True,
248
+ include_stop: bool = True,
249
+ ) -> tuple[MayBe[D], Iterator[D]]:
250
+ """Short circuit version of a right reduce.
251
+
252
+ Useful for infinite and non-reversible iterables.
253
+
254
+ Behavior for default arguments will
255
+
256
+ - right reduce finite iterable
257
+ - start folding at end (of a possibly infinite iterable)
258
+ - continue reducing right until beginning
259
+
260
+ :param iterable: iterable to be reduced from the right
261
+ :param f: two parameter function, second parameter for accumulated value
262
+ :param start: delay starting the fold until it returns true
263
+ :param stop: prematurely stop the fold when it returns true
264
+ :param include_start: if true, include fold starting value in fold
265
+ :param include_stop: if true, include stopping value in fold
266
+ :return: tuple of a MayBe of the folded value and iterator of remaining iterables
267
+
268
+ """
269
+ it_start, it_rest = take_while_split(iterable, negate(start))
270
+ list1 = list(it_start)
271
+ if include_start:
272
+ try:
273
+ begin = next(it_rest)
274
+ except StopIteration:
275
+ pass
276
+ else:
277
+ list1.append(begin)
278
+
279
+ list1.reverse()
280
+ it_reduce, it_stop = take_while_split(list1, negate(stop))
281
+
282
+ mb_reduced = maybe_fold_left(it_reduce, swap(f))
283
+ if include_stop:
284
+ try:
285
+ end = next(it_stop)
286
+ except StopIteration:
287
+ pass
288
+ else:
289
+ if mb_reduced:
290
+ mb_reduced = MayBe(f(end, mb_reduced.get()))
291
+ else:
292
+ mb_reduced = MayBe(end)
293
+
294
+ return (mb_reduced, it_rest)
@@ -0,0 +1,148 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Module pythonic_fp.iterables.merging"""
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Iterable, Iterator
20
+ from enum import auto, Enum
21
+
22
+ __all__ = [
23
+ 'MergeEnum',
24
+ 'concat',
25
+ 'merge',
26
+ 'exhaust',
27
+ 'blend',
28
+ ]
29
+
30
+ class MergeEnum(Enum):
31
+ """Iterable Blending Enums.
32
+
33
+ - **MergeEnum.Concat:** Concatenate first to last
34
+ - **MergeEnum.Merge:** Merge until one is exhausted
35
+ - **MergeEnum.Exhaust:** Merge until all are exhausted
36
+
37
+ """
38
+ Concat = auto()
39
+ Merge = auto()
40
+ Exhaust = auto()
41
+
42
+
43
+ def concat[D](*iterables: Iterable[D]) -> Iterator[D]:
44
+ """Sequentially concatenate multiple iterables together.
45
+
46
+ .. warning::
47
+ An infinite iterable will prevent subsequent iterables from
48
+ yielding any values.
49
+
50
+ .. note::
51
+
52
+ Performant to the standard library's ``itertools.chain``.
53
+
54
+ :param iterables: iterables to concatenate
55
+ :return: iterator of concatenated values from the iterables
56
+
57
+ """
58
+ for iterator in map(lambda x: iter(x), iterables):
59
+ while True:
60
+ try:
61
+ value = next(iterator)
62
+ yield value
63
+ except StopIteration:
64
+ break
65
+
66
+
67
+ def merge[D](
68
+ *iterables: Iterable[D],
69
+ yield_partials: bool = False
70
+ ) -> Iterator[D]:
71
+ """Merge together ``iterables`` until one is exhausted.
72
+
73
+ .. note::
74
+
75
+ When ``yield_partials`` is true, then any unmatched values from other iterables
76
+ already yielded when the first iterable is exhausted are yielded. This prevents
77
+ data lose if any of the iterables are iterators with external references.
78
+
79
+ :param iterables: iterables to merge until one gets exhausted
80
+ :param yield_partials: yield any unpaired yielded values from other iterables
81
+ :return: iterator of merged values from the iterables until one is exhausted
82
+
83
+ """
84
+ iter_list = list(map(lambda x: iter(x), iterables))
85
+ values = []
86
+ if (num_iters := len(iter_list)) > 0:
87
+ while True:
88
+ try:
89
+ for ii in range(num_iters):
90
+ values.append(next(iter_list[ii]))
91
+ yield from values
92
+ values.clear()
93
+ except StopIteration:
94
+ break
95
+ if yield_partials:
96
+ yield from values
97
+
98
+
99
+ def exhaust[D](*iterables: Iterable[D]) -> Iterator[D]:
100
+ """Merge together multiple iterables until all are exhausted.
101
+
102
+ :param iterables: iterables to exhaustively merge
103
+ :return: iterator of merged values from the iterables until all are exhausted
104
+
105
+ """
106
+ iter_list = list(map(lambda x: iter(x), iterables))
107
+ if (num_iters := len(iter_list)) > 0:
108
+ ii = 0
109
+ values = []
110
+ while True:
111
+ try:
112
+ while ii < num_iters:
113
+ values.append(next(iter_list[ii]))
114
+ ii += 1
115
+ yield from values
116
+ ii = 0
117
+ values.clear()
118
+ except StopIteration:
119
+ num_iters -= 1
120
+ if num_iters < 1:
121
+ break
122
+ del iter_list[ii]
123
+
124
+ yield from values
125
+
126
+
127
+ def blend[D](*iterables: Iterable[D],
128
+ merge_enum: MergeEnum = MergeEnum.Concat,
129
+ yield_partials: bool = False
130
+ ) -> Iterator[D]:
131
+ """Base merge behavior on name only parameters.
132
+
133
+ :param iterables: iterables to blend together
134
+ :param merge_enum: MergeEnum to determine merging behavior
135
+ :param yield_partials: yield yielded unpaired values from other iterables
136
+ :return: an iterator of type D
137
+ :raises ValueError: when an unknown MergeEnum is given
138
+
139
+ """
140
+ match merge_enum:
141
+ case MergeEnum.Concat:
142
+ return concat(*iterables)
143
+ case MergeEnum.Merge:
144
+ return merge(*iterables, yield_partials = yield_partials)
145
+ case MergeEnum.Exhaust:
146
+ return exhaust(*iterables)
147
+
148
+ raise ValueError('Unknown MergeEnum given')
File without changes