-
-
Save hsavit1/c464deac6eaa7321072d to your computer and use it in GitHub Desktop.
Revisions
-
alskipp created this gist
Oct 21, 2015 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,29 @@ extension SequenceType { func find(predicate: Generator.Element -> Bool) -> Generator.Element? { for x in self { if predicate(x) { return x } } return .None } } infix operator <|> {} // Alternative for Optional - return `lhs` if non-nil, otherwise return `rhs` func <|> <A>(lhs:A?, rhs:A?) -> A? { return lhs.map { $0 } ?? rhs } // Find the first element in SequenceType argument that matches an element in `self` extension SequenceType where Generator.Element: Equatable { func findFirst<S:SequenceType where S.Generator.Element == Generator.Element>(xs: S) -> Generator.Element? { return xs.reduce(.None) { acc, x in acc <|> self.find { $0 == x } } } } // examples: [3,29,9,23].findFirst(20...30) // .Some(23) [3,29,9,23].findFirst([50, 9, 3]) // .Some(9) ["a","b","c"].findFirst(["x","b"]) // .Some("b")