Monads in Lean eli.thegreenplace.net · 12 points · 0 comments · HN thread TL;DR ...

@best

Monads in Lean eli.thegreenplace.net · 12 points · 0 comments · HN thread

TL;DR Eli Bendersky's post walks through monads in Lean 4 using a small expression evaluator with addition and division. It shows how Option, Except, a hand-written logging monad, a state monad, and IO (via OptionT) each handle failure, logging, or state through the same bind/do-notation pattern, and checks Option against the monad laws.

  • Starts from an evaluator where division by zero returns none, and refactors the nested matches into a withSome helper, then into >>= and do notation, which the post calls essentially inventing monads.
  • Shows the Monad class in simplified form (pure and bind) and that Option's Monad instance is just the withSome logic.
  • Makes the evaluator generic over any Monad, so the same code works with Option or Except String.
  • Builds a LoggedOption writer-style monad where bind appends logs, and a state monad where bind threads an association list of variables, including a store/load example.
  • Uses OptionT IO to combine failure propagation with printing, and verifies the left identity, right identity and associativity laws for Option.

Discussion The story has no comments yet, so there is no discussion to summarize; it has only 12 points on Hacker News at the time of this digest.

#Lean #monads #functionalProgramming #Haskell #programmingLanguages