Skip to content

Instantly share code, notes, and snippets.

@amonshiz
Last active August 29, 2015 14:12
Show Gist options
  • Save amonshiz/c99719a4963b6db00fb8 to your computer and use it in GitHub Desktop.
Save amonshiz/c99719a4963b6db00fb8 to your computer and use it in GitHub Desktop.
Haskell style find for Swift Sliceable collections.
func find<S : Sliceable>(domain: S, isValue: (S.Generator.Element) -> Bool) -> S.Index? {
return find(domain, domain.startIndex, isValue)
}
func find<S : Sliceable>(domain: S, startingIndex: S.Index, isValue: (S.Generator.Element) -> Bool) -> S.Index? {
if startingIndex == domain.endIndex {
return nil
}
if isValue(domain[startingIndex]) {
return startingIndex
}
return find(domain, startingIndex.successor(), isValue)
}
/**
Usage
let origRanges: [HalfOpenInterval<Float>] = [0..<2, 2..<4, 4..<6]
let rIndex = find(origRanges) {
$0 ~= 2.5
}
if let ri = rIndex {
println(origRanges[rIndex]) // 2.0..<4.0
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment