Skip to content

Instantly share code, notes, and snippets.

@Pre1
Created September 14, 2016 13:45
Show Gist options
  • Save Pre1/bd788374a7dd5bd7f6a9fa2ce873b79c to your computer and use it in GitHub Desktop.
Save Pre1/bd788374a7dd5bd7f6a9fa2ce873b79c to your computer and use it in GitHub Desktop.
precedencegroup RangePattern {
associativity: left
lowerThan: RangeFormationPrecedence
}
infix operator .. : RangePattern
extension Float {
var samePrecision: Float {
return Float(description) ?? 0.0
}
}
// precisions may vary for some values.
func ..<T: FloatingPoint>(f: T, r: ClosedRange<T>) -> [T] {
guard f < r.lowerBound && f != r.lowerBound
else { return [] }
return sequence(first: [f, r.lowerBound]) {
if $0.contains(where: {$0 >= r.upperBound}) { return nil }
return $0 + [($0.last!) + (r.lowerBound - f)]
}.map {$0}.last!
}
// same precision accross all values.
// more info: https://bugs.swift.org/browse/SR-2062
// limitation: only work for Float aka Flaot32
func ..(f: Float, r: ClosedRange<Float>) -> [Float] {
guard f < r.lowerBound && f != r.lowerBound
else { return [] }
return sequence(first: [f, r.lowerBound]) {
if $0.contains(where: {$0 >= r.upperBound}) { return nil }
return $0 + [(($0.last!) + (r.lowerBound - f)).samePrecision]
}.lazy.map {$0}.last!
}
1..3...10 // => [1, 3, 5, 7, 9, 11]
2..4...10 // => [2, 4, 6, 8, 10]
1..1.5...4 // => [1, 1.5, 2, 2.5, 3, 3.5, 4]
2..4.2...10 // => [2, 4.2, 6.4, 8.6, 10.8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment