Last active
September 8, 2024 20:15
-
-
Save robert-king/3ef2646e9d5700337853df03745f369b to your computer and use it in GitHub Desktop.
memo function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::hash::Hash; | |
use std::{collections::HashMap, thread, time::Duration}; | |
fn factorial(n: i32) -> i32 { | |
if n <= 1 { | |
return 1; | |
} | |
thread::sleep(Duration::from_millis(100)); | |
factorial(n - 1).wrapping_mul(n) | |
} | |
fn memo<F, X, R>(f: F) -> impl FnMut(X) -> R | |
where | |
F: Fn(X) -> R, | |
X: Hash + Eq + Copy, | |
R: Copy, | |
{ | |
let mut cache: HashMap<X, R> = HashMap::new(); | |
move |x| { | |
if let Some(&ans) = cache.get(&x) { | |
return ans; | |
} | |
let ans = f(x); | |
cache.insert(x, ans); | |
ans | |
} | |
} | |
fn main() { | |
println!("{}", factorial(5)); | |
println!("{}", factorial(5)); | |
let mut mf = memo(factorial); | |
println!("{}", mf(5)); | |
println!("{}", mf(5)); | |
println!("{}", mf(5)); | |
println!("{}", mf(5)); | |
let double = |x| { | |
thread::sleep(Duration::from_millis(1_000)); | |
x*2 | |
}; | |
let mut memoized_double = memo(double); | |
println!("{}", memoized_double(22)); | |
println!("{}", memoized_double(22)); | |
println!("{}", memoized_double(22)); | |
println!("{}", memoized_double(22)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment