Skip to content

Instantly share code, notes, and snippets.

@WorldDownTown
Forked from Nirma/map_filter_reduce.swift
Created January 24, 2016 06:29
Show Gist options
  • Save WorldDownTown/500750ac148c0c78ddb4 to your computer and use it in GitHub Desktop.
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.
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