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 map function in terms of reduce

The reduction pattern is so powerful that every other function that traverses a list can be specified in terms of it. Let's develop a map function in terms of reduce:

func mapIntermsOfReduce<Element, ElementResult>(elements: [Element], transform: (Element) -> ElementResult) -> [ElementResult] {     return reduce(elements: elements, initial: [ElementResult]()) {         $0 + [transform( $1 )]     } } let result = mapIntermsOfReduce(elements: numbers, transform: { $0 + 2 }) 

The result is identical to our map function's result that we developed earlier in this chapter. This is a good example to understand the basics of reduce.

In the function body, we provide elements and an initial empty array of ElementResult, and ...

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