Lazy Computation Example: Fibonacci Sequence
Overview
The Fibonacci sequence is a classic example of a problem that can benefit from lazy computation. The sequence is defined recursively as:
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2) for n > 1
A naive recursive implementation would result in exponential time complexity due to repeated calculations. We can use lazy computation to store and reuse previously computed values.
Implementation
#include <functional>
#include <iostream>
#include <unordered_map>
// Define a lazy type
template<typename T>
using lazy = std::function<T()>;
// Function to memoize a lazy computation
template<typename T>
lazy<T> memoize(lazy<T> computation, std::unordered_map<int, T>& cache, int n) {
if (cache.find(n) != cache.end()) {
return [=]() { return cache[n]; };
} else {
auto result = computation();
cache[n] = result;
return [=]() { return result; };
}
}
// Compute Fibonacci sequence using lazy computation
lazy<int> fibonacci(int n, std::unordered_map<int, lazy<int>>& cache) {
if (n <= 1) {
return [=]() { return n; };
}
if (cache.find(n) != cache.end()) {
return cache[n];
}
auto fib_n_1 = fibonacci(n - 1, cache);
auto fib_n_2 = fibonacci(n - 2, cache);
auto computation = [=]() {
int result = fib_n_1() + fib_n_2();
return result;
};
cache[n] = memoize(computation, {}, n);
return cache[n];
}
int main() {
std::unordered_map<int, lazy<int>> cache;
int n = 10; // Compute Fibonacci(10)
auto fib_n = fibonacci(n, cache);
std::cout << "Fibonacci(" << n << ") = " << fib_n() << std::endl;
return 0;
}
Explanation
- We define a
lazy type as a std::function that returns a value of type T.
- The
memoize function takes a lazy computation, a cache, and an index n. If the result is already cached, it returns a lazy function that returns the cached value. Otherwise, it computes the result, stores it in the cache, and returns a lazy function that returns the result.
- The
fibonacci function computes the n-th Fibonacci number using lazy computation. It uses a cache to store previously computed values.
- In the
main function, we compute the 10th Fibonacci number using lazy computation and print the result.
This implementation has a time complexity of O(n), which is a significant improvement over the naive recursive implementation.