Skip to content

Instantly share code, notes, and snippets.

@johnynek
Created November 25, 2013 06:55
Show Gist options
  • Select an option

  • Save johnynek/7637347 to your computer and use it in GitHub Desktop.

Select an option

Save johnynek/7637347 to your computer and use it in GitHub Desktop.
MergeableMap in rust. The idea is to give a store that can "merge" arbitrary associative operations with no GC. That and fool around with rust.
// compiles with rustc 0.8
use std::hashmap::HashMap;
use std::container::MutableMap;
use std::util::swap;
use std::to_str::ToStr;
trait Semigroup {
fn plus(&self, that: ~Self) -> ~Self;
}
impl Semigroup for int {
fn plus(&self, mut that: ~int) -> ~int {
(*that) += *self;
return that
}
}
pub trait MergeableMap<K, V: Semigroup>: MutableMap<K, ~V> {
fn merge(&mut self, k: K, v: ~V) -> Option<~V> {
let new_val = match self.find(&k) {
Some(existing) => existing.plus(v),
None => v
};
self.swap(k, new_val)
}
}
impl <K: IterBytes + Eq, V: Semigroup> MergeableMap<K, V> for HashMap<K, ~V> {}
// Not sure why this isn't working by default
fn show<T:ToStr>(item: &~T) -> ~str {
item.to_str()
}
fn main() {
let mut m : HashMap<~str, ~int> = HashMap::new();
println(m.merge(~"key1", ~2).map(|it| -> ~str { show(it) }).to_str());
// prints: None
println(m.merge(~"key1", ~10).map(|it| -> ~str { show(it) }).to_str());
// prints: Some(2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment