Memoize Recursive Calls With HashMap

A RefCell-wrapped HashMap caches each recursive result, so repeated subtrees are looked up instead of recomputed and the cache length shows reuse.

RustData Integrity

Code

rustsnippet
22 lines
use std::cell::RefCell;
use std::collections::HashMap;

// memoization: a cache hit returns immediately; a miss recurses and then stores
fn ways(n: u32, cache: &RefCell<HashMap<u32, u64>>) -> u64 {
    if n <= 2 {
        return n as u64;
    }
    if let Some(hit) = cache.borrow().get(&n) {
        return *hit;
    }
    let value = ways(n - 1, cache) + ways(n - 2, cache);
    cache.borrow_mut().insert(n, value);
    value
}

fn main() {
    let cache = RefCell::new(HashMap::new());
    println!("stairs(10) = {}", ways(10, &cache));
    println!("stairs(30) = {}", ways(30, &cache));
    println!("cached entries: {}", cache.borrow().len());
}

How it works

The part worth importing is the functions ways and main — everything else is wiring.

What to watch for

  • No dependency resolution happens here; the toolchain alone suffices.

Applying it

Entry signature: fn ways(n: u32, cache: &RefCell<HashMap<u32, u64>>) -> u64

Look for the stairs(10) =, stairs(30) =, cached entries: prefixes as the file executes; they connect every printed line to the step behind it.

There are 1 call inside main — ways — executed top to bottom.

Statements that matter

fn ways(n: u32, cache: &RefCell<HashMap<u32, u64>>) -> u64 {
    if n <= 2 {
        return n as u64;
    }
    if let Some(hit) = cache.borrow().get(&n) {
        return *hit;
    }
    let value = ways(n - 1, cache) + ways(n - 2, cache);
    cache.borrow_mut().insert(n, value);
    value
}

Interactive Tools for This Topic

FAQ

What does Memoize Recursive Calls With HashMap print when run?
The script runs standalone; its 3 labeled outputs include `stairs(10) =`, `stairs(30) =`, `cached entries:`.