scan icon indicating copy to clipboard operation
scan copied to clipboard

All or nothing

Open Stebalien opened this issue 11 years ago • 1 comments

When parsing input, I quite often use an all or nothing approach (as in your example). However, as written, this library makes this a little cumbersome because each piece is stored in a separate Option. For me at least, the following would be more usable:

match scanln!("{u32} {s}") {
    Some((year, place)) => { /* something */ },
    None => ()
}

If you want to return where the parsing failed, you could use a result:

match scanln!("{u32} {s}") {
    Ok((year, place)) => { /* something */ },
    Err(0) => println!("please enter a year first"),
    Err(1) => println!("please enter your name"),
    Err(_) => fail!("Wouldn't it be nice if rust could statically prove this case unreachable?...")
}

Stebalien avatar Sep 27 '14 06:09 Stebalien

So you want it to expand to something like this?

{
    fn do_it() -> Result<(u32, String), uint> {
        let mut pb = ::scan::stdin(true);
        pb.whitespace();
        let a0 = pb.unsigned_integer().map(|v| v as u32);
        if a0.is_none() {
            return Err(0);
        }
        pb.whitespace();
        let a2 = Some(pb.word());
        pb.whitespace();
        Ok((a0.unwrap(), a2.unwrap()))
    }
    do_it()
};

I think that's reasonable. PRs are welcome.

mahkoh avatar Sep 27 '14 12:09 mahkoh