Last active
September 2, 2017 16:53
-
-
Save killercup/1c48ef7279a947fcaba9e59ea2673386 to your computer and use it in GitHub Desktop.
Count words
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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