this post was submitted on 14 Aug 2023
1429 points (98.0% liked)
Programmer Humor
27048 readers
597 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
"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 a0somewhere andx + 0 == xto hold. Like"foo" + "" == "foo"in the case of strings, just as an example.In Rust,
ResultandOptionactually are monads. Let's takeOptionas example:pure xisSome(x)a >>= bisa.and_then(b)Then we have:
Some(x).and_then(f)≡f(x)x.and_then(Some)≡xm.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.
Resultnames>>=and_then, just likeOptiondoes so the code reads the same but you'll have to choose betweenOptionorResultin the type signature, the code can't be properly generic over it.