Skip to content

Instantly share code, notes, and snippets.

@Nirma
Last active January 24, 2016 14:16
Show Gist options
  • Save Nirma/ab2f970d052590384524 to your computer and use it in GitHub Desktop.
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.
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