From 8628adc10d6ed2384f47e842f1bec2ecba079d93 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Sat, 21 Jul 2018 13:45:10 +0300 Subject: Change: use a type alias for WordCounts --- src/main.rs | 66 +++++++++++++++++++++++++------------------------------------ 1 file changed, 27 insertions(+), 39 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2162453..aef750d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,6 @@ use std::env; use std::fs::File; use std::io; use std::io::BufRead; -use std::ops; use std::collections::HashMap; @@ -12,7 +11,7 @@ fn main() -> io::Result<()> { let mut f = File::open(&filename)?; let mut reader = io::BufReader::new(f); let counts = count_words(&mut reader)?; - counts.print(10) + print(&counts, 10) } Ok(()) } @@ -22,7 +21,7 @@ fn count_words(reader: &mut io::BufReader) -> io::Result { let mut counts = WordCounts::new(); for line in reader.lines() { let line = line?; - counts += count_words_in_line(&line); + add_counts(&mut counts, &count_words_in_line(&line)); } Ok(counts) } @@ -36,60 +35,49 @@ fn count_words_in_line(line: &str) -> WordCounts { word.push(c); } else { if !word.is_empty() { - counts.count(word.clone()); + count(&mut counts, word.clone()); word.clear(); } } } if !word.is_empty() { - counts.count(word.clone()); + count(&mut counts, word.clone()); } counts } -struct WordCounts { - counts: HashMap, -} +type WordCounts = HashMap; -impl WordCounts { - fn new() -> Self { - WordCounts { - counts: HashMap::new(), - } - } +fn count(counts: &mut WordCounts, word: String) { + add(counts, word, 1); +} - fn count(&mut self, word: String) { - self.add(word, 1); - } - fn add(&mut self, word: String, count: u32) { - let counter = self.counts.entry(word).or_insert(0); - *counter += count; - } - - fn print(&self, max: usize) { - let mut top = Vec::new(); - for (word, count) in self.counts.iter() { - top.push((count, word)); - if top.len() > max { - top.sort(); - top.reverse(); - top.truncate(max); - } - } - for (count, word) in top.iter() { - println!("{} {}", count, word); - } +fn add_counts(counts: &mut WordCounts, other: &WordCounts) { + for (word, count) in other.iter() { + add(counts, word.to_string(), *count); } } -impl ops::AddAssign for WordCounts { - fn add_assign(&mut self, other: WordCounts) { - for (word, count) in other.counts.iter() { - self.add(word.to_string(), *count); +fn add(counts: &mut WordCounts, word: String, count: u32) { + let counter = counts.entry(word).or_insert(0); + *counter += count; +} + +fn print(counts: &WordCounts, max: usize) { + let mut top = Vec::new(); + for (word, count) in counts.iter() { + top.push((count, word)); + if top.len() > max { + top.sort(); + top.reverse(); + top.truncate(max); } } + for (count, word) in top.iter() { + println!("{} {}", count, word); + } } -- cgit v1.2.1