-
Notifications
You must be signed in to change notification settings - Fork 446
/
Copy pathIntersperse.swift
669 lines (585 loc) · 21 KB
/
Intersperse.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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Intersperse
//===----------------------------------------------------------------------===//
/// A sequence that presents the elements of a base sequence of elements with a
/// separator between each of those elements.
public struct InterspersedSequence<Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let separator: Base.Element
@inlinable
internal init(base: Base, separator: Base.Element) {
self.base = base
self.separator = separator
}
}
extension InterspersedSequence: Sequence {
/// The iterator for an `InterspersedSequence` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal enum State {
case start
case element(Base.Element)
case separator
}
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline
internal let separator: Base.Element
@usableFromInline
internal var state = State.start
@inlinable
internal init(iterator: Base.Iterator, separator: Base.Element) {
self.iterator = iterator
self.separator = separator
}
@inlinable
public mutating func next() -> Base.Element? {
// After the start, the state flips between element and separator. Before
// returning a separator, a check is made for the next element as a
// separator is only returned between two elements. The next element is
// stored to allow it to be returned in the next iteration.
switch state {
case .start:
state = .separator
return iterator.next()
case .separator:
guard let next = iterator.next() else { return nil }
state = .element(next)
return separator
case .element(let element):
state = .separator
return element
}
}
}
@inlinable
public func makeIterator() -> InterspersedSequence<Base>.Iterator {
Iterator(iterator: base.makeIterator(), separator: separator)
}
}
extension InterspersedSequence: Collection where Base: Collection {
/// A position in an `InterspersedSequence` instance.
public struct Index: Comparable {
@usableFromInline
internal enum Representation: Equatable {
case element(Base.Index)
case separator(next: Base.Index)
}
@usableFromInline
internal let representation: Representation
@inlinable
internal init(representation: Representation) {
self.representation = representation
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs.representation, rhs.representation) {
case let (.element(li), .element(ri)),
let (.separator(next: li), .separator(next: ri)),
let (.element(li), .separator(next: ri)):
return li < ri
case let (.separator(next: li), .element(ri)):
return li <= ri
}
}
@inlinable
internal static func element(_ index: Base.Index) -> Self {
Self(representation: .element(index))
}
@inlinable
internal static func separator(next: Base.Index) -> Self {
Self(representation: .separator(next: next))
}
}
@inlinable
public var startIndex: Index {
base.startIndex == base.endIndex ? endIndex : .element(base.startIndex)
}
@inlinable
public var endIndex: Index {
.separator(next: base.endIndex)
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex")
switch i.representation {
case let .element(index):
return .separator(next: base.index(after: index))
case let .separator(next):
return .element(next)
}
}
@inlinable
public subscript(position: Index) -> Element {
switch position.representation {
case .element(let index): return base[index]
case .separator: return separator
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case let (.element(element), .separator(next: separator)):
return 2 * base.distance(from: element, to: separator) - 1
case let (.separator(next: separator), .element(element)):
return 2 * base.distance(from: separator, to: element) + 1
case let (.element(start), .element(end)),
let (.separator(start), .separator(end)):
return 2 * base.distance(from: start, to: end)
}
}
@inlinable
public func index(_ index: Index, offsetBy distance: Int) -> Index {
distance >= 0
? offsetForward(index, by: distance)
: offsetBackward(index, by: -distance)
}
@inlinable
public func index(
_ index: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
if distance >= 0 {
return limit >= index
? offsetForward(index, by: distance, limitedBy: limit)
: offsetForward(index, by: distance)
} else {
return limit <= index
? offsetBackward(index, by: -distance, limitedBy: limit)
: offsetBackward(index, by: -distance)
}
}
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetForward(
_ index: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance >= 0)
assert(limit >= index)
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
case let (.element(index), .element(limit), true),
let (.separator(next: index), .element(limit), false):
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
.map { .element($0) }
case let (.element(index), .element(limit), false),
let (.element(index), .separator(next: limit), false),
let (.separator(next: index), .element(limit), true),
let (.separator(next: index), .separator(next: limit), true):
return base.index(index, offsetBy: (distance + 1) / 2, limitedBy: limit)
.map { .separator(next: $0) }
case let (.element(index), .separator(next: limit), true),
let (.separator(next: index), .separator(next: limit), false):
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
.flatMap { $0 == limit ? nil : .element($0) }
}
}
@inlinable
internal func offsetBackward(
_ index: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance >= 0)
assert(limit <= index)
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
case let (.element(index), .element(limit), true),
let (.element(index), .separator(next: limit), true),
let (.separator(next: index), .element(limit), false),
let (.separator(next: index), .separator(next: limit), false):
return base.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
.map { .element($0) }
case let (.element(index), .separator(next: limit), false),
let (.separator(next: index), .separator(next: limit), true):
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
.map { .separator(next: $0) }
case let (.element(index), .element(limit), false),
let (.separator(next: index), .element(limit), true):
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
.flatMap { $0 == limit ? nil : .separator(next: $0) }
}
}
}
extension InterspersedSequence: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't move before startIndex")
switch i.representation {
case let .element(index):
return .separator(next: index)
case let .separator(next):
return .element(base.index(before: next))
}
}
}
extension InterspersedSequence: RandomAccessCollection
where Base: RandomAccessCollection {}
extension InterspersedSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension InterspersedSequence: LazyCollectionProtocol
where Base: LazySequenceProtocol & Collection {}
//===----------------------------------------------------------------------===//
// InterspersedMap
//===----------------------------------------------------------------------===//
/// A sequence over the results of applying a closure to the sequence's
/// elements, with a separator that separates each pair of adjacent transformed
/// values.
@usableFromInline
internal struct InterspersedMapSequence<Base: Sequence, Result> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let transform: (Base.Element) -> Result
@usableFromInline
internal let separator: (Base.Element, Base.Element) -> Result
}
extension InterspersedMapSequence: Sequence {
@usableFromInline
internal struct Iterator: IteratorProtocol {
@usableFromInline
internal enum State {
case start
case element(Base.Element)
case separator(previous: Base.Element)
}
@usableFromInline
internal var base: Base.Iterator
@usableFromInline
internal let transform: (Base.Element) -> Result
@usableFromInline
internal let separator: (Base.Element, Base.Element) -> Result
@usableFromInline
internal var state = State.start
@inlinable
internal init(
base: Base.Iterator,
transform: @escaping (Base.Element) -> Result,
separator: @escaping (Base.Element, Base.Element) -> Result
) {
self.base = base
self.transform = transform
self.separator = separator
}
@inlinable
internal mutating func next() -> Result? {
switch state {
case .start:
guard let first = base.next() else { return nil }
state = .separator(previous: first)
return transform(first)
case .separator(let previous):
guard let next = base.next() else { return nil }
state = .element(next)
return separator(previous, next)
case .element(let element):
state = .separator(previous: element)
return transform(element)
}
}
}
@inlinable
internal func makeIterator() -> Iterator {
Iterator(
base: base.makeIterator(),
transform: transform,
separator: separator)
}
}
extension InterspersedMapSequence: Collection where Base: Collection {
@usableFromInline
internal struct Index: Comparable {
@usableFromInline
internal enum Representation {
case element(Base.Index)
case separator(previous: Base.Index, next: Base.Index)
}
@usableFromInline
internal let representation: Representation
@inlinable
internal init(representation: Representation) {
self.representation = representation
}
@inlinable
internal static func element(_ index: Base.Index) -> Self {
Self(representation: .element(index))
}
@inlinable
internal static func separator(previous: Base.Index, next: Base.Index) -> Self {
Self(representation: .separator(previous: previous, next: next))
}
@inlinable
internal static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs.representation, rhs.representation) {
case let (.element(lhs), .element(rhs)),
let (.separator(_, next: lhs), .separator(_, next: rhs)):
return lhs == rhs
case (.element, .separator), (.separator, .element):
return false
}
}
@inlinable
internal static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs.representation, rhs.representation) {
case let (.element(lhs), .element(rhs)),
let (.separator(_, next: lhs), .separator(_, next: rhs)),
let (.element(lhs), .separator(_, next: rhs)),
let (.separator(previous: lhs, _), .element(rhs)):
return lhs < rhs
}
}
}
@inlinable
internal var startIndex: Index {
base.isEmpty ? endIndex : .element(base.startIndex)
}
@inlinable
internal var endIndex: Index {
.separator(previous: base.endIndex, next: base.endIndex)
}
@inlinable
internal func index(after index: Index) -> Index {
switch index.representation {
case .element(let index):
let next = base.index(after: index)
return .separator(previous: index, next: next)
case .separator(_, let next):
return .element(next)
}
}
@inlinable
internal subscript(position: Index) -> Result {
switch position.representation {
case .element(let index):
return transform(base[index])
case let .separator(previous, next):
return separator(base[previous], base[next])
}
}
@inlinable
internal func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case let (.element(lhs), .element(rhs)),
let (.separator(_, next: lhs), .separator(_, next: rhs)):
return 2 * base.distance(from: lhs, to: rhs)
case let (.element(lhs), .separator(_, next: rhs)):
return 2 * base.distance(from: lhs, to: rhs) - 1
case let (.separator(_, next: lhs), .element(rhs)):
return 2 * base.distance(from: lhs, to: rhs) + 1
}
}
@inlinable
internal func index(_ index: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return index }
return distance > 0
? offsetForward(index, by: distance)
: offsetBackward(index, by: -distance)
}
@inlinable
internal func index(
_ index: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
guard distance != 0 else { return index }
if distance > 0 {
return limit >= index
? offsetForward(index, by: distance, limitedBy: limit)
: offsetForward(index, by: distance)
} else {
return limit <= index
? offsetBackward(index, by: -distance, limitedBy: limit)
: offsetBackward(index, by: -distance)
}
}
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetForward(
_ index: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit >= index)
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
case let (.element(index), .element(limit), true),
let (.separator(_, next: index), .element(limit), false):
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
.map { .element($0) }
case let (.element(index), .element(limit), false),
let (.element(index), .separator(_, next: limit), false),
let (.separator(_, next: index), .element(limit), true),
let (.separator(_, next: index), .separator(_, next: limit), true):
return base.index(index, offsetBy: (distance - 1) / 2, limitedBy: limit)
.flatMap {
guard $0 != limit else { return nil }
let next = base.index(after: $0)
return next == base.endIndex
? endIndex
: .separator(previous: $0, next: next)
}
case let (.element(index), .separator(_, next: limit), true),
let (.separator(_, next: index), .separator(_, next: limit), false):
return base.index(index, offsetBy: distance / 2, limitedBy: limit)
.flatMap { $0 == limit ? nil : .element($0) }
}
}
@inlinable
internal func offsetBackward(
_ index: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit <= index)
switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
case let (.element(index), .element(limit), true),
let (.element(index), .separator(_, next: limit), true),
let (.separator(_, next: index), .element(limit), false),
let (.separator(_, next: index), .separator(_, next: limit), false):
return base.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
.map { .element($0) }
case let (.element(index), .separator(_, next: limit), false),
let (.separator(_, next: index), .separator(_, next: limit), true):
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
.map { .separator(previous: base.index($0, offsetBy: -1), next: $0) }
case let (.element(index), .element(limit), false),
let (.separator(_, next: index), .element(limit), true):
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
.flatMap {
$0 == limit
? nil
: .separator(previous: base.index($0, offsetBy: -1), next: $0)
}
}
}
}
extension InterspersedMapSequence: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
internal func index(before index: Index) -> Index {
switch index.representation {
case .element(let index):
let previous = base.index(before: index)
return .separator(previous: previous, next: index)
case let .separator(previous, next):
let index = next == base.endIndex ? base.index(before: next) : previous
return .element(index)
}
}
}
extension InterspersedMapSequence.Index: Hashable
where Base.Index: Hashable
{
@inlinable
internal func hash(into hasher: inout Hasher) {
switch representation {
case .element(let base):
hasher.combine(false)
hasher.combine(base)
case .separator(_, let next):
hasher.combine(true)
hasher.combine(next)
}
}
}
extension InterspersedMapSequence: LazySequenceProtocol {}
extension InterspersedMapSequence: LazyCollectionProtocol
where Base: Collection {}
//===----------------------------------------------------------------------===//
// interspersed(with:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence containing elements of this sequence with the given
/// separator inserted in between each element.
///
/// Any value of the sequence's element type can be used as the separator.
///
/// ```
/// for value in [1,2,3].interspersed(with: 0) {
/// print(value)
/// }
/// // 1
/// // 0
/// // 2
/// // 0
/// // 3
/// ```
///
/// The following shows a String being interspersed with a Character:
/// ```
/// let result = "ABCDE".interspersed(with: "-")
/// print(String(result))
/// // "A-B-C-D-E"
/// ```
///
/// - Parameter separator: Value to insert in between each of this sequence’s
/// elements.
/// - Returns: The interspersed sequence of elements.
///
/// - Complexity: O(1)
@inlinable
public func interspersed(
with separator: Element
) -> InterspersedSequence<Self> {
InterspersedSequence(base: self, separator: separator)
}
}
//===----------------------------------------------------------------------===//
// lazy.interspersedMap(_:with:)
//===----------------------------------------------------------------------===//
extension LazySequenceProtocol {
/// Returns a sequence over the results of applying a closure to the
/// sequence's elements, with a separator that separates each pair of adjacent
/// transformed values.
///
/// The transformation closure lets you intersperse a sequence using a
/// separator of a different type than the original's sequence's elements.
/// Each separator is produced by a closure that is given access to the
/// two elements in the original sequence right before and after it.
///
/// let strings = [1, 2, 2].interspersedMap(String.init,
/// with: { $0 == $1 ? " == " : " != " })
/// print(strings.joined()) // "1 != 2 == 2"
///
@usableFromInline
internal func interspersedMap<Result>(
_ transform: @escaping (Element) -> Result,
with separator: @escaping (Element, Element) -> Result
) -> InterspersedMapSequence<Elements, Result> {
InterspersedMapSequence(
base: elements,
transform: transform,
separator: separator)
}
}