Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Map and filter implemented with a version of reduce taking a list as input.
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