Refactor Dictionary creation
This commit is contained in:
parent
b552804b56
commit
ac99a172cc
1 changed files with 28 additions and 17 deletions
45
src/main.rs
45
src/main.rs
|
@ -17,19 +17,31 @@ struct Dictionary {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Dictionary {
|
impl Dictionary {
|
||||||
fn load_from_iterable(&mut self, lines: impl Iterator<Item = Result<String, Error>>) {
|
fn words_from_iterable(
|
||||||
let mut it = lines;
|
lines: impl Iterator<Item = Result<String, Error>>,
|
||||||
|
) -> Result<Vec<String>, Error> {
|
||||||
// aux_set is used only to deduplicate
|
// aux_set is used only to deduplicate
|
||||||
// so we're still using a normal Vec, and perform deduplication at load time
|
// so we're still using a normal Vec, and perform deduplication at load time
|
||||||
let mut aux_set = HashSet::new();
|
let mut aux_set = HashSet::new();
|
||||||
for line in it.by_ref() {
|
lines
|
||||||
let line = line.unwrap();
|
.filter(|res| match res {
|
||||||
let word = line_to_word(line);
|
Ok(word) => aux_set.insert(word.clone()),
|
||||||
if !aux_set.contains(&word) {
|
_ => false,
|
||||||
//println!("Inserisco: {}", word);
|
})
|
||||||
aux_set.insert(word.clone());
|
.collect()
|
||||||
self.words.push(word);
|
}
|
||||||
}
|
|
||||||
|
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 fname = &args[1];
|
||||||
let pattern = &args[2];
|
let pattern = &args[2];
|
||||||
|
|
||||||
let f = File::open(fname).unwrap();
|
let d = Dictionary::load(fname.to_string());
|
||||||
let buf = BufReader::new(&f);
|
|
||||||
let mut d = Dictionary::default();
|
|
||||||
d.load_from_iterable(buf.lines());
|
|
||||||
|
|
||||||
//let filter = matches_regexp(pattern);
|
//let filter = matches_regexp(pattern);
|
||||||
let filter = is_anagram(pattern);
|
let filter = is_anagram(pattern);
|
||||||
for w in d.words.iter().filter(filter) {
|
if let Ok(dict) = d {
|
||||||
println!("{}", w)
|
for w in dict.words.iter().filter(filter) {
|
||||||
}
|
println!("{}", w);
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
Reference in a new issue