You are viewing a single thread.
View all comments View context
4 points
*

“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.

permalink
report
parent
reply

Programmer Humor

!programmer_humor@programming.dev

Create post

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

Community stats

  • 3.2K

    Monthly active users

  • 1K

    Posts

  • 37K

    Comments