6 Lazy evaluation

This chapter covers

  • Calculating values when they’re needed
  • Caching values of pure functions
  • Modifying the quicksort algorithm to sort only parts of the collection
  • Using expression templates for lazy evaluation of expressions
  • Representing infinite or near-infinite structures

Calculations take time. Say you have two matrices—A and B—and you’re told you may need their product at some point. One thing you could do is to immediately calculate the product, and it’ll be ready when you need it:

auto P = A * B;

The problem is that you may end up not needing the product at all—and you wasted your precious CPU cycles calculating it.

An alternative approach is to say if someone needs it, P should be calculated as A * B. Instead ...

Get Functional Programming in C++ now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.