Created
November 25, 2013 06:55
-
-
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.
This file contains hidden or 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
| // 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