Last active
January 24, 2016 14:16
-
-
Save Nirma/ab2f970d052590384524 to your computer and use it in GitHub Desktop.
Map and filter implemented with a version of reduce taking a list as input.
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 reduce<T,R>(list: [T], block: (([R],T) -> R?)) -> [R]? { | |
var acc = [R]() | |
for x in list { | |
if let val = block(acc, x) { | |
acc += [val] | |
} | |
} | |
return acc | |
} | |
func filter<T>(list: [T], filterPass: (T -> Bool)) -> [T]?{ | |
return reduce(list) { | |
return filterPass($1) ? $1 : nil | |
} | |
} | |
func map<T,R>(list:[T], mapClosure:(T -> R)) -> [R]? { | |
return reduce(list) { | |
return mapClosure($1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment