Skip to content

Instantly share code, notes, and snippets.

@erica
Last active February 29, 2016 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/3cd5633b9e139844aa5a to your computer and use it in GitHub Desktop.
Save erica/3cd5633b9e139844aa5a to your computer and use it in GitHub Desktop.
/// A `GeneratorType` for `DoubleStrideThrough`.
public struct DoubleStrideThroughGenerator : GeneratorType {
let start: Double
let end: Double
let stride: Double
var iteration: Int = 0
var done: Bool = false
public init(start: Double, end: Double, stride: Double) {
(self.start, self.end, self.stride) = (start, end, stride)
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
public mutating func next() -> Double? {
if done {
return nil
}
let current = start + Double(self.iteration) * stride
iteration += 1
// if stride > 0.0 ? current >= end : current <= end {
if signbit(current - end) == signbit(stride) { // thanks Joe Groff
if current >= end {
done = true
return current
}
return nil
}
return current
}
}
public struct DoubleStrideThrough : SequenceType {
let start: Double
let end: Double
let stride: Double
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> DoubleStrideThroughGenerator {
return DoubleStrideThroughGenerator(
start: start, end: end, stride: stride)
}
init(start: Double, end: Double, stride: Double) {
_precondition(stride != 0, "stride size must not be zero")
self.start = start
self.end = end
self.stride = stride
}
}
public extension Double {
public func fstride(
through end: Double, by stride: Double
) -> DoubleStrideThrough {
return DoubleStrideThrough(
start: self, end: end, stride: stride)
}
}
print(Array(0.0.fstride(through: 2.0, by: 0.1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment