O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The filter function in terms of reduce

It is also possible to develop a filter function in terms of reduce:

func filterIntermsOfReduce<Element>(elements: [Element], predicate: (Element) -> Bool) -> [Element] {     return reduce(elements: elements, initial: []) {         predicate($1) ? $0 + [ $1 ] : $0     } } let result = filterIntermsOfReduce(elements: numbers) { $0 % 2 == 0 } 

Again, the result is identical to our previously developed filter function.

In the function body, we provide elements, an empty initial array, and finally, predicate as a combinator.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required