swift function programming

使用reduce来实现map和filter功能

let a = [1,2,3]let b = a.reduce(0, combine: +)extension Array {func mMap(transform: Element -> U) -> [U] {

return reduce([], combine: { $0 + [transform($1)]})

}

func mFilter (includeElement: Element -> Bool) -> [Element] {

return reduce([]) {

includeElement($1) ? $0 + [$1] : $0

}

}

}

let c = a.mMap({ $0 + 2})

let d = a.mFilter({ $0 > 2})

print(c)

print(d)

你可能感兴趣的:(swift function programming)