“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.
In Rust, Result and Option actually are monads. Let’s take Option as example:
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.
“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 a0
somewhere andx + 0 == x
to hold.In Rust,
Result
andOption
actually are monads. Let’s takeOption
as example:pure x
isSome(x)
a >>= b
isa.and_then(b)
Then we have:
Some(x).and_then(f)
≡f(x)
x.and_then(Some)
≡x
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 likeOption
does so the code reads the same but you’ll have to choose betweenOption
orResult
in the type signature, the code can’t be properly generic over it.