Skip to content

Instantly share code, notes, and snippets.

@apparentsoft
Last active August 29, 2015 14:12
Show Gist options
  • Save apparentsoft/cc0a67de7301351f1ae2 to your computer and use it in GitHub Desktop.
Save apparentsoft/cc0a67de7301351f1ae2 to your computer and use it in GitHub Desktop.
func catOptionals<T,S where S:SequenceType, S.Generator.Element == Optional<T>>(optionals: S) -> [T] {
return reduce(optionals, []) { (acc, value: T?) -> [T] in
switch value {
case let .Some(v): return acc + [v]
default: return acc
}
}
}
let a: [Int?] = [4,7,nil,8]
catOptionals(a)
// returns [4,7,8]
@rnapier
Copy link

rnapier commented Dec 23, 2014

Note that array+array in Swift has lousy performance compared to Haskell's List prepend. It forces a lot of real copying (not just copy-on-write). This function has O(n^2) performance if I remember correctly.

@casademora
Copy link

I guess I'll stick with a O(2n) pass with a filter then map will be better than a O(n^2) for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment