Add improvements to insert_with_key

This commit adds a lower-level implementation of the generic
`insert_with_key` which I expect to be faster. Now insert could be
defined with insert_with_key, too, although I'm not sure we want to do that.

This also clarifies the tests a bit and adds an `insert_with` function.
This commit is contained in:
Kevin Cantu 2012-11-20 23:33:31 -08:00 committed by Brian Anderson
parent 7b13ef7d50
commit ff4075e553
5 changed files with 132 additions and 19 deletions

View file

@ -69,7 +69,7 @@ fn find(mm: HashMap<~[u8], uint>, key: ~str) -> uint {
// given a map, increment the counter for a key
fn update_freq(mm: HashMap<~[u8], uint>, key: &[u8]) {
let key = vec::slice(key, 0, key.len());
mm.insert_with_key(|k,v,v1| {v + v1}, key, 1);
mm.insert_with(key, 1, |v,v1| { v+v1 });
}
// given a ~[u8], for each window call a function

View file

@ -66,7 +66,7 @@ fn find(mm: HashMap<~[u8], uint>, key: ~str) -> uint {
// given a map, increment the counter for a key
fn update_freq(mm: HashMap<~[u8], uint>, key: &[u8]) {
let key = vec::slice(key, 0, key.len());
mm.insert_with_key(|k,v,v1| {v + v1}, key, 1);
mm.insert_with(key, 1, |v,v1| { v+v1 });
}
// given a ~[u8], for each window call a function

View file

@ -61,13 +61,20 @@ impl<T: Copy> cat<T> : Map<int, T> {
else { None }
}
fn insert_with_key(ff: fn(+k: int, +v0: T, +v1: T) -> T, +key: int, +val: T) -> bool {
fn insert_with_key(+key: int, +val: T, ff: fn(+k: int, +v0: T, +v1: T) -> T) -> bool {
match self.find(key) {
None => return self.insert(key, val),
Some(copy orig) => return self.insert(key, ff(key, orig, val))
}
}
fn insert_with(+key: int, +val: T, ff: fn(+v0: T, +v1: T) -> T) -> bool {
match self.find(key) {
None => return self.insert(key, val),
Some(copy orig) => return self.insert(key, ff(orig, val))
}
}
fn remove(+k:int) -> bool {
match self.find(k) {