Skip to content

Commit 3685945

Browse files
treemanalexcrichton
authored andcommitted
Main examples for TrieSet and TrieMap.
1 parent a524928 commit 3685945

File tree

1 file changed

+67
-2
lines changed

1 file changed

+67
-2
lines changed

src/libcollections/trie.rs

Lines changed: 67 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,44 @@ enum Child<T> {
3636
Nothing
3737
}
3838

39-
/// A map as a radix trie.
39+
/// A map implemented as a radix trie.
40+
///
41+
/// # Example
42+
///
43+
/// ```
44+
/// use std::collections::TrieMap;
45+
///
46+
/// let mut map = TrieMap::new();
47+
/// map.insert(27, "Olaf");
48+
/// map.insert(1, "Edgar");
49+
/// map.insert(13, "Ruth");
50+
/// map.insert(1, "Martin");
51+
///
52+
/// assert_eq!(map.len(), 3);
53+
/// assert_eq!(map.find(&1), Some(&"Martin"));
54+
///
55+
/// if !map.contains_key(&90) {
56+
/// println!("Nobody is keyed 90");
57+
/// }
58+
///
59+
/// // Update a key
60+
/// match map.find_mut(&1) {
61+
/// Some(value) => *value = "Olga",
62+
/// None => (),
63+
/// }
64+
///
65+
/// map.remove(&13);
66+
/// assert_eq!(map.len(), 2);
67+
///
68+
/// // Print the key value pairs, ordered by key.
69+
/// for (key, value) in map.iter() {
70+
/// // Prints `1: Olga` then `27: Olaf`
71+
/// println!("{}: {}", key, value);
72+
/// }
73+
///
74+
/// map.clear();
75+
/// assert!(map.is_empty());
76+
/// ```
4077
pub struct TrieMap<T> {
4178
root: TrieNode<T>,
4279
length: uint
@@ -421,7 +458,35 @@ impl<S: Writer, T: Hash<S>> Hash<S> for TrieMap<T> {
421458
}
422459
}
423460

424-
/// A set as a radix trie.
461+
/// A set implemented as a radix trie.
462+
///
463+
/// # Example
464+
///
465+
/// ```
466+
/// use std::collections::TrieSet;
467+
///
468+
/// let mut set = TrieSet::new();
469+
/// set.insert(6);
470+
/// set.insert(28);
471+
/// set.insert(6);
472+
///
473+
/// assert_eq!(set.len(), 2);
474+
///
475+
/// if !set.contains(&3) {
476+
/// println!("3 is not in the set");
477+
/// }
478+
///
479+
/// // Print contents in order
480+
/// for x in set.iter() {
481+
/// println!("{}", x);
482+
/// }
483+
///
484+
/// set.remove(&6);
485+
/// assert_eq!(set.len(), 1);
486+
///
487+
/// set.clear();
488+
/// assert!(set.is_empty());
489+
/// ```
425490
#[deriving(Hash, PartialEq, Eq)]
426491
pub struct TrieSet {
427492
map: TrieMap<()>

0 commit comments

Comments
 (0)