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

Lazy lists

So far, we have implemented a linked list and a stack as a list. One of the key concepts in FP is the concept of lazy evaluation. We can make our list lazy so that the elements will be evaluated once we access them. We need to change node in such a way that it will return a function containing list as next, instead of the list itself. The function will be evaluated when it is called; therefore, our list will be lazy.

We start with modifying our node case. In our LinkedList example, next was of the LinkedList<Element> type. To make our list lazy, we will modify next to be a function that returns our list:

enum LazyList<Element: Equatable> {     case end     case node(data: Element, next: () -> LazyList<Element>) } 

As we can see in the ...

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