-
-
Save WorldDownTown/500750ac148c0c78ddb4 to your computer and use it in GitHub Desktop.
Map and filter implemented with a version of reduce taking list as its reduce argument.
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