Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I have the same concern, but I'm not sure how efficiently you could get monads to compile. It would be possible (but tricky) to come up with a macro for haskell's do syntax that would translate

    monad!(
      sock <= TcpStream::connect(host, port);
      let parser = Parser::new(&mut sock as &mut Reader);
      parser.parse_value()
    )
to

    TcpStream::connect(host, port).map(|sock| {
      let parser = Parser::new(&mut sock as &mut Reader);
      parser.parse_value()
    })
but could you get that to compile to the same machine code as this?

    match TcpStream::connect(host, port) {
      Ok(stream) => {
        let parser = Parser::new(&mut sock as &mut Reader);
        parser.parse_value()
      },
      Error(e) => { return e; }
    }
Rust has the same "don't pay for what you don't use" mantra as C++, and introducing the overhead of stack closure in the canonical error handling method would be unacceptable. It might be possible to optimize monadic code as nicely as e.g. iterators, but I'm not convinced.


> but could you get that to compile to the same machine code as this?

Well not exactly because the second snippet is not equivalent to the first one (it doesn't wrap the result of parse_value() back into an Ok(), and thus I guess wouldn't compile), but aside from that yes: Result.map is trivially implemented in terms of match and (almost always) inlined: https://github.com/rust-lang/rust/blob/master/src/libcore/re... and the closure is itself inlined. So the resulting assembly should be the exact same between the two versions


The only difference between the two is inlining the map method, no? This may be the "sufficiently smart compiler" fallacy, but that really doesn't seem very hard.

Certainly I've been very impressed with the performance I've seen from Haskell (and Scala) on real-world problems, though I appreciate that's not quite the same thing, and a more realtime-suitable language that had the same level of expressiveness would definitely be a Good Thing.


> The only difference between the two is inlining the map method, no? This may be the "sufficiently smart compiler" fallacy, but that really doesn't seem very hard.

It doesn't even rely on a smart compiler: https://github.com/rust-lang/rust/blob/master/src/libcore/re...

The #[inline] attribute is defined as a "standard (though very strong) inline hint" (there's also #[inline(never)] and #[inline(always)])




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: