Last active
April 24, 2018 18:09
-
-
Save khanlou/ea7a9f006c9cc4e09dd91327f61c77d9 to your computer and use it in GitHub Desktop.
tweaks by @ericasadun
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// A strided non-contiguous sequence of elements that incorporates | |
/// every nth element of a base sequence. | |
public struct StridedSequence<BaseSequence: Sequence> : Sequence, IteratorProtocol { | |
public mutating func next() -> BaseSequence.Element? { | |
defer { | |
for _ in 0 ..< _strideLength - 1 { | |
let _ = _iterator.next() | |
} | |
} | |
return _iterator.next() } | |
/// Access only through `Sequence.striding(by:)` | |
internal init(_ sequence: BaseSequence, stride strideLength: Int) { | |
_iterator = sequence.makeIterator() | |
_strideLength = strideLength | |
} | |
internal var _iterator: BaseSequence.Iterator | |
internal var _strideLength: Int | |
} | |
extension Sequence { | |
/// Returns a strided iterator of sequence elements. The | |
/// stride length is set to incorporate every nth element. | |
/// | |
/// - Parameter strideLength: the distance for each stride | |
/// - Returns: A strided sequence of values | |
func striding(by strideLength: Int) -> StridedSequence<Self> { | |
return StridedSequence(self, stride: strideLength) | |
} | |
} |
erica
commented
Apr 24, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment