Last active
August 29, 2015 14:02
-
-
Save mbrandonw/535295308a89da6a50fd to your computer and use it in GitHub Desktop.
`compact` function in Swift
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
func compact <A> (xs: [A?]) -> [A] { | |
return xs.reduce([]) { accum, x in | |
if let x = x { | |
return accum + [x] | |
} | |
return accum | |
} | |
} | |
var xs: [Int?] = [1, 2, nil, 3] | |
compact(xs) // => [1, 2, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment