Created
October 21, 2015 17:35
-
-
Save alskipp/a18dcff5d09bf104603e to your computer and use it in GitHub Desktop.
Swift: Find the first element of a Sequence that matches an element of another Sequence
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
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment