You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
genmarkov/src/main.rs

48 lines
1.1 KiB

4 years ago
use chain::{
Chain,
};
use std::{
io::{
BufRead,
self,
},
};
fn buffered_read_all_lines<T: BufRead+?Sized, F: FnMut(&str) -> io::Result<()>>(input: &mut T, mut then: F) -> io::Result<usize>
{
let mut buffer = String::new();
let mut read;
let mut total=0;
while {read = input.read_line(&mut buffer)?; read!=0} {
then(&buffer[..])?;
buffer.clear();
total += read;
}
Ok(total)
}
fn main() {
let stdin = io::stdin();
let mut stdin = stdin.lock();
let mut chain = Chain::new();
buffered_read_all_lines(&mut stdin, |string| {
chain.feed(&string.split_whitespace()
.filter(|word| !word.is_empty())
.map(|s| s.to_owned()).collect::<Vec<_>>());
Ok(())
}).expect("Failed to read from stdin");
if !chain.is_empty() {
if let Some(num) = std::env::args().skip(1).next() {
let sz: usize = num.parse().expect("Cannot parse number of tokens to generate");
for string in chain.str_iter_for(sz) {
println!("{}", string);
}
} else {
println!("{}", chain.generate_str());
}
}
}