Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Created December 9, 2014 16:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airspeedswift/da4180aaebbf7387117a to your computer and use it in GitHub Desktop.
Save airspeedswift/da4180aaebbf7387117a to your computer and use it in GitHub Desktop.
Re-using ZipGenerator2 to create a sliding window
func findFirst<S: SequenceType>(seq: S, predicate: S.Generator.Element -> Bool) -> S.Generator.Element? {
for x in seq {
if predicate(x) { return x }
}
return nil
}
func not<T>(predicate: T -> Bool) -> (T -> Bool) {
return { x in !predicate(x) }
}
func all<S: SequenceType>(s: S, predicate: S.Generator.Element -> Bool) -> Bool {
return findFirst(s, not(predicate)) == nil
}
public func dropFirst<S: SequenceType>(seq: S) -> SequenceOf<S.Generator.Element> {
return SequenceOf { ()->GeneratorOf<S.Generator.Element> in
var g = seq.generate()
let first = g.next()
// if you prefer your dropFirst to explodinate on empty
// sequences, add an assert(first != nil) here...
return GeneratorOf {
// shouldn't call GeneratorType.next()
// after it's returned nil the first time
first == nil ? nil : g.next()
}
}
}
public struct SlidingWindow2<S: SequenceType> : SequenceType {
public typealias Generator = ZipGenerator2<S.Generator,SequenceOf<S.Generator.Element>.Generator>
private let _base: S
public init(_ source: S) { _base = source }
public func generate() -> Generator {
let g1 = _base.generate()
let g2 = dropFirst(_base).generate()
return ZipGenerator2(g1, g2)
}
}
public func isSorted<S: SequenceType
where S.Generator.Element: Comparable>
(s: S) -> Bool {
return all(SlidingWindow2(s)) { $0 <= $1 }
}
isSorted([] as [Int])
isSorted([1])
isSorted([1,2,3,4])
isSorted([1,2,3,3])
isSorted([2,1])
isSorted([1,2,3,2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment