Created
December 9, 2018 11:59
-
-
Save brosenan/f0eea4c21d6d69f65889d17f9df0be79 to your computer and use it in GitHub Desktop.
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::collections::HashMap; | |
use std::hash::Hash; | |
struct Memoize<F, T1, T2> where F: Fn(&T1) -> T2 { | |
cache: HashMap<T1, T2>, | |
func: F, | |
} | |
impl<F, T1, T2> Memoize<F, T1, T2> where F: Fn(&T1) -> T2, T1: Eq + Hash, T2: Clone { | |
fn new(func: F) -> Memoize<F, T1, T2> { | |
Memoize {cache: HashMap::new(), func} | |
} | |
fn get(&mut self, k : T1) -> T2 { | |
match self.cache.get(&k) { | |
Some(v) => v.clone(), | |
None => { | |
let v = (self.func)(&k); | |
self.cache.insert(k, v.clone()); | |
v | |
} | |
} | |
} | |
} | |
fn main() { | |
let mut f = Memoize::new(|x| x + 2); | |
println!("Hello, world! {} {}", f.get(2), f.get(5)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Memoization example in Rust