O'Reilly logo

Swift 3 Functional Programming 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 list

So far, we implemented a linked list and a stack as a list. One of the key concepts in functional programming 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 ...

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