Refactor Dictionary creation

This commit is contained in:
Blallo 2020-05-19 10:52:23 +02:00
parent b552804b56
commit ac99a172cc
No known key found for this signature in database
GPG key ID: 0CBE577C9B72DC3F

View file

@ -17,19 +17,31 @@ struct Dictionary {
}
impl Dictionary {
fn load_from_iterable(&mut self, lines: impl Iterator<Item = Result<String, Error>>) {
let mut it = lines;
fn words_from_iterable(
lines: impl Iterator<Item = Result<String, Error>>,
) -> Result<Vec<String>, Error> {
// aux_set is used only to deduplicate
// so we're still using a normal Vec, and perform deduplication at load time
let mut aux_set = HashSet::new();
for line in it.by_ref() {
let line = line.unwrap();
let word = line_to_word(line);
if !aux_set.contains(&word) {
//println!("Inserisco: {}", word);
aux_set.insert(word.clone());
self.words.push(word);
}
lines
.filter(|res| match res {
Ok(word) => aux_set.insert(word.clone()),
_ => false,
})
.collect()
}
fn load(fname: String) -> Result<Self, Error> {
let maybe_words = File::open(fname)
.and_then(|open_f| Ok(BufReader::new(open_f)))
.and_then(|buf| Self::words_from_iterable(buf.lines()));
match maybe_words {
Ok(words) => Ok(Dictionary {
words,
iter_position: 0,
}),
Err(err) => Err(err),
}
}
}
@ -84,14 +96,13 @@ fn main() {
let fname = &args[1];
let pattern = &args[2];
let f = File::open(fname).unwrap();
let buf = BufReader::new(&f);
let mut d = Dictionary::default();
d.load_from_iterable(buf.lines());
let d = Dictionary::load(fname.to_string());
//let filter = matches_regexp(pattern);
let filter = is_anagram(pattern);
for w in d.words.iter().filter(filter) {
println!("{}", w)
}
if let Ok(dict) = d {
for w in dict.words.iter().filter(filter) {
println!("{}", w);
}
};
}