• barsoap
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    1 year ago

    “Some generic class” with specific methods and laws, Monads are an algebraic structure and you want those laws included same as if you enable some type to use + you want to have a 0 somewhere and x + 0 == x to hold. Like "foo" + "" == "foo" in the case of strings, just as an example.

    In Rust, Result and Option actually are monads. Let’s take Option as example:

    • pure x is Some(x)
    • a >>= b is a.and_then(b)

    Then we have:

    • Left identity: Some(x).and_then(f)f(x)
    • Right identity: x.and_then(Some)x
    • Associativity: m.and_then(g).and_then(h)m.and_then(|x| g(x).and_then(h))

    Why those laws? Because following them avoids surprises like x + 0 /= x.

    Rust’s type system isn’t powerful enough to have a Monad trait (lack of HKTs) hence why you can’t write code that works with any type that implements that kind of interface. Result names >>= and_then, just like Option does so the code reads the same but you’ll have to choose between Option or Result in the type signature, the code can’t be properly generic over it.