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

map, filter, and reduce

You may have wondered if we are going to be able to apply higher-order functions such as map, filter, and reduce to our linked list. We have implemented our linked list with a recursive enum and the recursive pattern is well suited to higher-order functions.

Let's start with map:

func map<T>(_ transform: (Element) -> T) -> LinkedList<T> {     switch self {     case .end:         return .end     case .node(let data, let next):         return transform(data) <| next.map(transform)     } } 

Using this method, we will be able to transform elements in our linked list. Nothing fancy here; we use the same cons operator that we defined before. The following statement will test our method:

 let mappedFunctionalLL = functionalLinkedList.map { $0 * 2 ...

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