6 ms·
This is superficially nice, but let's not forget that we would hardly do this in practice. It's much more likely that we would write your Go version with some e
by jstimpfle 10y ago
This is superficially nice, but let's not forget that we would hardly do this in practice. It's much more likely that we would write your Go version with some error handling or logging messages added in.
Practical concerns aside, in Haskell you get these things from the Maybe monad without extra syntax or macros:
foo >>= bar >>= baz
- webkike 10y agoI'm pretty sure that ">>=" is "extra syntax". The only difference is in Haskell any function with two arguments can be interpreted as infix.
- jstimpfle 10y agoIt's not built-in syntax, not even a macro. Just a binary function.
- saghm 10y agoI 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.
- jstimpfle 10y ago"extra syntax or macros" refers to OP's example of "?". That ">>=" is not magic is exactly what I said (meant to say).
- saghm 10y agoI 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.
- neikos 10y agoIf you don't mind unstable you can implement it yourself for Option. https://doc.rust-lang.org/src/core/up/src/libcore/ops.rs.html#2815-2830 https://doc.rust-lang.org/src/core/up/src/libcore/ops.rs.htm... I am sure it will come soon (tm) though
- saghm 10y agoI 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.
- jzelinskie 10y agoI 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/mdo https://crates.io/crates/mdo
- deleted 10y ago[deleted]