Skip to content

Instantly share code, notes, and snippets.

@killercup
Last active September 2, 2017 16:53
Show Gist options
  • Save killercup/1c48ef7279a947fcaba9e59ea2673386 to your computer and use it in GitHub Desktop.
Save killercup/1c48ef7279a947fcaba9e59ea2673386 to your computer and use it in GitHub Desktop.
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