Skip to content

Instantly share code, notes, and snippets.

@rnapier
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rnapier/6e411cb20ac82b0bd8ed to your computer and use it in GitHub Desktop.
Save rnapier/6e411cb20ac82b0bd8ed to your computer and use it in GitHub Desktop.
isSorted messing around
// see also https://gist.github.com/griotspeak/8bb4c46611fc90d3043b
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
}
extension Optional {
func flatMap<U>(f: T -> U?) -> U? {
if let x = self.map(f) { return x }
else { return nil }
}
}
public struct SlidingWindowGenerator2<G: GeneratorType> : GeneratorType {
public typealias Element = (G.Element, G.Element)
private var g: G
private var prev: G.Element?
private var exhausted: Bool = false
public init(_ g: G) {
self.g = g
self.prev = self.g.next()
}
public mutating func next() -> Element? {
precondition(!self.exhausted,
"Called next() after it has returned nil")
let result:Element? = self.prev.flatMap { prev in
let curr = self.g.next()
self.prev = curr
return curr.map { curr in (prev, curr) }
}
self.exhausted = (result == nil)
return result
}
}
public struct SlidingWindow2<S: SequenceType> : SequenceType {
public typealias Generator = SlidingWindowGenerator2<S.Generator>
private let s: S
public init(_ s: S) { self.s = s }
public func generate() -> Generator { return Generator(self.s.generate()) }
}
public func isSorted<S: SequenceType
where S.Generator.Element: Comparable>
(s: S) -> Bool {
return all(SlidingWindow2(s)) { $0 <= $1 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment