Skip to content

Instantly share code, notes, and snippets.

@adrientetar
Last active December 31, 2015 10:29
Show Gist options
  • Select an option

  • Save adrientetar/7973349 to your computer and use it in GitHub Desktop.

Select an option

Save adrientetar/7973349 to your computer and use it in GitHub Desktop.
use std::io::buffered::BufferedReader;
use std::io::fs::File;
fn main() {
let pairs = read_int_pairs();
for &(a,b) in pairs.iter() {
println!("{:4.4d}, {:4.4d}", a, b);
}
}
fn read_int_pairs() -> ~[(int,int)] {
let mut pairs = ~[];
let args = std::os::args();
// Path is a little strange in that it takes a generic by-value, rather than by reference
let path = match args.get_opt(1) {
Some(f) => f,
None => fail!("No input file parameter found!")
};
let mut reader = BufferedReader::new(File::open(&Path::new(path.as_slice())));
for line in reader.lines() {
// while !reader.eof() {
// 1. Read a line of input.
// let line = reader.read_line().unwrap();
// 2. Split the line into fields ("words").
let fields = line.words().to_owned_vec();
// 3. Match the vector of fields against a vector pattern.
match fields {
// 4. When the line had two fields:
[a, b] => {
// 5. Try parsing both fields as ints.
match (from_str::<int>(a), from_str::<int>(b)) {
// 6. If parsing succeeded for both, push both.
(Some(a), Some(b)) => pairs.push((a,b)),
// 7. Ignore non-int fields.
_ => ()
}
}
// 8. Ignore lines that don't have 2 fields.
_ => ()
}
}
pairs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment