On 23/05/13 16:13, Ziad Hatahet wrote:
Say we want to implement the following function:
fn add(x: Option<int>, y: Option<int>) -> Option<int> { ... }
Some functional languages, like Haskell and Scala offer some sort of a
"do" notation to make unwrapping multiple Option type values easier.
add :: Maybe Int -> Maybe Int -> Maybe Int
add mx my = do
x <- mx
y <- my
return (x + y)
Is there an equivalent construct in Rust?
--
Ziad
I just whipped up a very basic do-notation syntax extension[1] (it can't
be called "do!" unfortunately), it was much easier than I was expecting.
The following compiles fine:
fn main () {
let x = do_!(bind a = Some(1);
bind b = None;
let res = a + b;
Some(res));
println(fmt!("%?", x))
}
and prints None (or Some(3), if you change the None to Some(2)). It
works for anything that defines a method called "chain" (e.g. Result),
but there's no generic return equivalent yet, so that has to be changed
for each type. (I chose to use bind rather than <- (or similar) for
parsing ease.)
Huon
[1]: https://github.com/huonw/rust/tree/do-notation
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev