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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.