Created
June 11, 2014 08:51
-
-
Save vhbit/b95ea993ea62fbbba47e to your computer and use it in GitHub Desktop.
Comment on error handling example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn result_from_option<T, E>(a: Option<T>, f: || -> E) -> Result<T, E> { | |
match a { | |
Some(a) => Ok(a), | |
_ => Err(f()) | |
} | |
} | |
fn slurp_file(file: &Path) -> Result<Vec<LabelPixel>, SlurpError> { | |
use std::{result, option}; | |
let file: File = try!(File::open(file).map_err(|e| FailedIo(e))); | |
let mut file = BufferedReader::new(file); | |
let lines = file.lines() | |
.skip(1) | |
.map(|line| { | |
let line = try!(line.map_err(|e| FailedIo(e))); | |
let mut splits = line.as_slice().trim().split(',').map(|x| from_str(x)); | |
// .and_then is flattening Option<Option<int>> to Option<int>. | |
let label: int = try!(result_from_option(splits.next().and_then(|x| x), || InvalidInput)); | |
let pixels: Vec<int> = try!(result_from_option(option::collect(splits), || InvalidInput)); | |
Ok(LabelPixel { | |
label: label, | |
pixels: pixels | |
}) | |
}); | |
result::collect(lines) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment