-
Notifications
You must be signed in to change notification settings - Fork 446
/
Copy pathReductions.swift
620 lines (554 loc) · 17.9 KB
/
Reductions.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: - Exclusive Reductions
extension LazySequenceProtocol {
/// Returns a sequence containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(0, +)
/// print(Array(runningTotal))
///
/// // prints [0, 1, 3, 6, 10]
/// ```
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: A sequence of the initial value followed by the reduced
/// elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions<Result>(
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductionsSequence<Elements, Result> {
reductions(into: initial) { result, element in
result = transform(result, element)
}
}
/// Returns a sequence containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(into: 0, +)
/// print(Array(runningTotal))
///
/// // prints [0, 1, 3, 6, 10]
/// ```
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: A sequence of the initial value followed by the reduced
/// elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions<Result>(
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductionsSequence<Elements, Result> {
ExclusiveReductionsSequence(
base: elements,
initial: initial,
transform: transform)
}
}
extension Sequence {
/// Returns an array containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].reductions(0, +)
/// print(runningTotal)
///
/// // prints [0, 1, 3, 6, 10]
/// ```
///
/// When `reductions(_:_:)` is called, the following steps occur:
///
/// 1. The `initial` result is added to an array of results.
/// 2. The `transform` closure is called with the `initial` result and the
/// first element of the sequence, appending the result to the array.
/// 3. The closure is called again repeatedly with the updated accumulating
/// result and each element of the sequence, adding each result to the
/// array.
/// 4. When the sequence is exhausted, the results array is returned to the
/// caller.
///
/// If the sequence has no elements, `transform` is never executed and
/// an array containing only the `initial` result is returned.
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: An array of the initial value followed by the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions<Result>(
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
try reductions(into: initial) { result, element in
result = try transform(result, element)
}
}
/// Returns an array containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].reductions(into: 0, +)
/// print(runningTotal)
///
/// // prints [0, 1, 3, 6, 10]
/// ```
///
/// When `reductions(into:_:_)` is called, the following steps occur:
///
/// 1. The `initial` result is added to an array of results.
/// 2. The `transform` closure is called with the `initial` result and the
/// first element of the sequence, appending the result to the array.
/// 3. The closure is called again repeatedly with the updated accumulating
/// result and each element of the sequence, adding each result to the
/// array.
/// 4. When the sequence is exhausted, the results array is returned to the
/// caller.
///
/// If the sequence has no elements, `transform` is never executed and
/// an array containing only the `initial` result is returned.
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving sequence.
/// - Returns: An array of the initial value followed by the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions<Result>(
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {
var output = [Result]()
output.reserveCapacity(underestimatedCount + 1)
output.append(initial)
var initial = initial
for element in self {
try transform(&initial, element)
output.append(initial)
}
return output
}
}
/// A sequence of applying a transform to the element of a sequence and the
/// previously transformed result.
public struct ExclusiveReductionsSequence<Base: Sequence, Result> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let initial: Result
@usableFromInline
internal let transform: (inout Result, Base.Element) -> Void
@inlinable
internal init(
base: Base,
initial: Result,
transform: @escaping (inout Result, Base.Element) -> Void
) {
self.base = base
self.initial = initial
self.transform = transform
}
}
extension ExclusiveReductionsSequence: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline
internal var current: Result?
@usableFromInline
internal let transform: (inout Result, Base.Element) -> Void
@inlinable
internal init(
iterator: Base.Iterator,
current: Result? = nil,
transform: @escaping (inout Result, Base.Element) -> Void
) {
self.iterator = iterator
self.current = current
self.transform = transform
}
@inlinable
public mutating func next() -> Result? {
guard let result = current else { return nil }
current = iterator.next().map { element in
var result = result
transform(&result, element)
return result
}
return result
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(
iterator: base.makeIterator(),
current: initial,
transform: transform)
}
}
extension ExclusiveReductionsSequence: Collection where Base: Collection {
public struct Index: Comparable {
@usableFromInline
internal enum Representation {
case base(Base.Index, Result)
case end
}
@usableFromInline
internal let representation: Representation
@inlinable
internal init(_ representation: Representation) {
self.representation = representation
}
@inlinable
public static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs.representation, rhs.representation) {
case (.base(let lhs, _), .base(let rhs, _)):
return lhs == rhs
case (.end, .end):
return true
case (.base, .end), (.end, .base):
return false
}
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs.representation, rhs.representation) {
case (.end, _):
return false
case (_, .end):
return true
case (.base(let lhs, _), .base(let rhs, _)):
return lhs < rhs
}
}
}
@inlinable
public var startIndex: Index {
Index(.base(base.startIndex, initial))
}
@inlinable
public var endIndex: Index {
Index(.end)
}
@inlinable
public subscript(position: Index) -> Result {
switch position.representation {
case .base(_, let result):
return result
case .end:
fatalError("Cannot get element of end index.")
}
}
@inlinable
public func index(after index: Index) -> Index {
switch index.representation {
case .base(base.endIndex, _):
return Index(.end)
case .base(let index, var result):
transform(&result, base[index])
return Index(.base(base.index(after: index), result))
case .end:
fatalError("Cannot get index after end index.")
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case let (.base(start, _), .base(end, _)):
return base.distance(from: start, to: end)
case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex) + 1
case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index) - 1
case (.end, .end):
return 0
}
}
}
extension ExclusiveReductionsSequence: LazySequenceProtocol {}
extension ExclusiveReductionsSequence: LazyCollectionProtocol
where Base: Collection {}
extension ExclusiveReductionsSequence.Index: Hashable
where Base.Index: Hashable
{
@inlinable
public func hash(into hasher: inout Hasher) {
switch representation {
case .base(let base, _):
hasher.combine(base)
case .end:
break
}
}
}
// MARK: - Inclusive Reductions
extension LazySequenceProtocol {
/// Returns a sequence containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].lazy.reductions(+)
/// print(Array(runningTotal))
///
/// // prints [1, 3, 6, 10]
/// ```
///
/// - Parameter transform: A closure that combines the previously reduced
/// result and the next element in the receiving sequence.
/// - Returns: A sequence of the reduced elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions(
_ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductionsSequence<Elements> {
InclusiveReductionsSequence(base: elements, transform: transform)
}
}
extension Sequence {
/// Returns an array containing the accumulated results of combining the
/// elements of the sequence using the given closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as a sequence.
///
/// ```
/// let runningTotal = [1, 2, 3, 4].reductions(+)
/// print(runningTotal)
///
/// // prints [1, 3, 6, 10]
/// ```
///
/// When `reductions(_:)` is called, the following steps occur:
///
/// 1. The `transform` closure is called with the first and second elements
/// of the sequence, appending the result to an array of results.
/// 2. The closure is called again repeatedly with the updated accumulating
/// result and the next element of the sequence, adding each result to the
/// array.
/// 3. When the sequence is exhausted, the results array is returned to the
/// caller.
///
/// If the sequence has no elements, `transform` is never executed and
/// an empty array is returned.
///
/// If the sequence has one element, `transform` is never executed and
/// an array containing only that first element is returned.
///
/// - Parameter transform: A closure that combines the previously reduced
/// result and the next element in the receiving sequence.
/// - Returns: An array of the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions(
_ transform: (Element, Element) throws -> Element
) rethrows -> [Element] {
var iterator = makeIterator()
guard let initial = iterator.next() else { return [] }
return try IteratorSequence(iterator).reductions(initial, transform)
}
}
public struct InclusiveReductionsSequence<Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let transform: (Base.Element, Base.Element) -> Base.Element
@inlinable
internal init(
base: Base,
transform: @escaping (Base.Element, Base.Element) -> Base.Element
) {
self.base = base
self.transform = transform
}
}
extension InclusiveReductionsSequence: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline
internal var element: Base.Element?
@usableFromInline
internal let transform: (Base.Element, Base.Element) -> Base.Element
@inlinable
internal init(
iterator: Base.Iterator,
transform: @escaping (Base.Element, Base.Element) -> Base.Element
) {
self.iterator = iterator
self.transform = transform
}
@inlinable
public mutating func next() -> Base.Element? {
guard let previous = element else {
element = iterator.next()
return element
}
guard let next = iterator.next() else { return nil }
element = transform(previous, next)
return element
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(), transform: transform)
}
}
extension InclusiveReductionsSequence: Collection where Base: Collection {
public struct Index: Comparable {
@usableFromInline
internal let base: Base.Index
@usableFromInline
internal let result: Element?
@inlinable
internal init(base: Base.Index, result: Element?) {
self.base = base
self.result = result
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.base < rhs.base
}
@inlinable
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.base == rhs.base
}
}
@inlinable
public var startIndex: Index {
Index(base: base.startIndex, result: base.first)
}
@inlinable
public var endIndex: Index {
Index(base: base.endIndex, result: nil)
}
@inlinable
public subscript(index: Index) -> Base.Element {
guard let result = index.result else {
fatalError("Can't subscript using endIndex")
}
return result
}
@inlinable
public func index(after index: Index) -> Index {
guard let result = index.result else {
fatalError("Can't advance past endIndex")
}
let index = base.index(after: index.base)
let nextResult = index == base.endIndex
? nil
: transform(result, base[index])
return Index(base: index, result: nextResult)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
base.distance(from: start.base, to: end.base)
}
}
extension InclusiveReductionsSequence: LazySequenceProtocol {}
extension InclusiveReductionsSequence: LazyCollectionProtocol
where Base: Collection {}
extension InclusiveReductionsSequence.Index: Hashable
where Base.Index: Hashable
{
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(base)
}
}
// MARK: - Scan
extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
@inlinable
public func scan<Result>(
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductionsSequence<Elements, Result> {
reductions(initial, transform)
}
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
@inlinable
public func scan<Result>(
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductionsSequence<Elements, Result> {
reductions(into: initial, transform)
}
}
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
@inlinable
public func scan<Result>(
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
try reductions(initial, transform)
}
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
@inlinable
public func scan<Result>(
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {
try reductions(into: initial, transform)
}
}
extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(_:) instead.")
@inlinable
public func scan(
_ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductionsSequence<Elements> {
reductions(transform)
}
}
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:) instead.")
@inlinable
public func scan(
_ transform: (Element, Element) throws -> Element
) rethrows -> [Element] {
try reductions(transform)
}
}