1415
Golang be like (i.imgur.com)
you are viewing a single comment's thread
view the rest of the comments
[-] barsoap@lemm.ee 4 points 1 year ago* (last edited 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.

this post was submitted on 14 Aug 2023
1415 points (98.0% liked)

Programmer Humor

19551 readers
336 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

founded 1 year ago
MODERATORS