Skip to content

Instantly share code, notes, and snippets.

Last active Sep 2, 2017
What would you like to do?
Count words
use std::collections::HashMap;
fn count_words(text: &str) -> HashMap<&str, usize> {
text.split(' ').fold(
|mut map, word| { *map.entry(word).or_insert(0) += 1; map }
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