Forked from rnapier/gist:6e411cb20ac82b0bd8ed
Last active
August 29, 2015 14:11
This file contains 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
// 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 SlidingWindow2<S: SequenceType> : SequenceType { | |
public typealias Generator = GeneratorOf<(S.Generator.Element, S.Generator.Element)> | |
private let s: S | |
public init(_ s: S) { self.s = s } | |
public func generate() -> Generator { | |
typealias G = S.Generator | |
typealias Element = (G.Element, G.Element) | |
var g: G = s.generate() | |
var prev: G.Element? = g.next() | |
var exhausted: Bool = false | |
return GeneratorOf { | |
precondition(!exhausted, "Called next() after it has returned nil") | |
let result: Element? = prev.flatMap { p in | |
let curr = g.next() | |
prev = curr | |
return curr.map { c in (p, c) } | |
} | |
exhausted = (result == nil) | |
return result | |
} | |
} | |
} | |
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