Re:Announcing Rust 1.13
by jzelinskie on Thursday November 10, 2016 @10:17PM
(#12927308)
I recently started checking out Rust and was quickly disappointed that it's near impossible to chain anything unless their signatures match perfectly. Subsequently, I found the `mdo` crate[0] to be rather useful, although I'm not sure how idiomatic it is. It's essentially a macro that implements Haskell's do-notation. Here's a snippet from the README:
let l = mdo! {
z =<< 1i32..11;
x =<< 1..z;
y =<< x..z;
when x * x + y * y == z * z;
ret ret((x, y, z))
}.collect::<Vec<_>>();
[0]: https://crates.io/crates/mdoI'm pretty sure that ">>=" is "extra syntax". The only difference is in Haskell any function with two arguments can be interpreted as infix.
It's not built-in syntax, not even a macro. Just a binary function.
I think this would actually be more comparable to the Either monad. Also, "without extra syntax or macros" is kind of a trivial distinction, as `>>=` is just a function, not some sort of magic.
That being said, I really wish there were some sort of equivalent of `try` or `?` for options in Rust. I don't feel like I want monads in Rust in general, but when dealing with options, I definitely miss the Maybe monad.
"extra syntax or macros" refers to OP's example of "?". That ">>=" is not magic is exactly what I said (meant to say).
I guess I'm not seeing why having a function rather than a macro is really that much of a distinction in this case. Either way, it's essentially just a namespaced block of code that compiles down to an AST fragment; I don't think the facts that one of them uses the stack and that they're compiled at slightly different times really make much of a difference here.
If you don't mind unstable you can implement it yourself for Option. https://doc.rust-lang.org/src/core/up/src/libcore/ops.rs.htm...
I am sure it will come soon (tm) though
I usually just implement a `try_option` macro, which works well enough. I just wish it were a built-in thing in the language, as I don't like having to implement it for every new project, but I really don't want to include an external crate just for one macro.
Practical concerns aside, in Haskell you get these things from the Maybe monad without extra syntax or macros: