Skip to content

Instantly share code, notes, and snippets.

@killercup
Last active Sep 2, 2017
Embed
What would you like to do?
Count words
use std::collections::HashMap;
fn count_words(text: &str) -> HashMap<&str, usize> {
text.split(' ').fold(
HashMap::new(),
|mut map, word| { *map.entry(word).or_insert(0) += 1; map }
)
}
#[test]
fn test1() {
let counts = count_words("lorem lorem ipsum");
assert_eq!(counts["lorem"], 2);
assert_eq!(counts["ipsum"], 1);
assert_eq!(counts.get("non-existing-word"), None);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment