#![expect(
clippy::print_stdout,
clippy::use_debug,
reason = "This example is for demonstration, not a test."
)]
use pretty_assertions::assert_eq;
use skiplist::{FnComparator, SkipMap};
fn main() {
let mut freq: SkipMap<String, usize> = SkipMap::new();
let words = ["the", "cat", "sat", "on", "the", "mat", "the", "cat"];
for word in words {
let count = freq.get(word).copied().unwrap_or(0);
freq.insert(word.to_owned(), count.saturating_add(1));
}
println!("Frequency of 'the': {:?}", freq.get("the"));
println!("Frequency of 'cat': {:?}", freq.get("cat"));
println!("Frequency of 'dog': {:?}", freq.get("dog"));
assert_eq!(freq.get("the"), Some(&3));
assert_eq!(freq.get("cat"), Some(&2));
assert_eq!(freq.get("dog"), None);
println!("\nAll word counts (sorted alphabetically):");
for (word, count) in &freq {
println!(" {word}: {count}");
}
let mut by_freq: SkipMap<(&str, usize), (), 16, _> =
SkipMap::with_comparator(FnComparator(|a: &(&str, usize), b: &(&str, usize)| {
b.1.cmp(&a.1).then(a.0.cmp(b.0))
}));
for (word, count) in &freq {
by_freq.insert((word.as_str(), *count), ());
}
println!("\nAll word counts (most frequent first):");
for ((word, count), ()) in &by_freq {
println!(" {word}: {count}");
}
let first_key = by_freq.first_key_value().map(|(k, ())| k);
assert_eq!(first_key, Some(&("the", 3)));
println!("\nDone!");
}