Zulip Chat Archive

Stream: mathlib4

Topic: Style RFC: prefer do notation in monadic code


Thomas Murrills (Oct 15 2025 at 16:22):

I’d like to propose documenting a style preference for do notation over Haskell-style monadic operators like >>=.

As far as I can tell, we already do this for the most part, but haven’t written it down. I think using do notation helps make code more readable and maintainable. :)

There are a couple of Haskell-style operators we do use occasionally in specific circumstances, like <$>, boolean monadic operators, and occasionally <|>.

My proposal would be to mention those, and allow some discretion on the part of the contributor/reviewer to use one of these common-enough Haskell-style operators when significantly more readable. (Maybe we’d want to discuss which ones exactly would be allowed.)

It’s been mentioned that we should also have a reference for Haskell-style monadic notation, and we could include this together with their do translations for those used to Haskell-style notation. (Possibly this should info should be in the docstrings for the notation as well, but that’s a separate topic.) I think this is a good idea! We could link to it from this section of the style guide.

Up to details, does this sound reasonable?

Michael Rothgang (Oct 15 2025 at 16:28):

I personally am in favour: I don't come from a Haskell background, and do notation is significantly more readable to me.

Eric Wieser (Oct 15 2025 at 16:34):

Note that in theory <$> and <*> notation can express implementations that are faster than the >>= generated by donotation

Eric Wieser (Oct 15 2025 at 16:34):

Eg <$> on an array monad can preallocate up front, and on a state monad it can in theory elide a reference count

Thomas Murrills (Oct 15 2025 at 16:35):

Interesting!

in theory

Do they? :eyes:

Thomas Murrills (Oct 15 2025 at 16:37):

If so—or even if they might confer an advantage over do in the future—it would, imo, make sense to allow these specific combinators, especially in performance-critical pieces of code.

Thomas Murrills (Oct 15 2025 at 16:38):

(But I’d like to distinguish them from the ones which don’t! :grinning_face_with_smiling_eyes:)

Eric Wieser (Oct 15 2025 at 16:40):

Attempted test-case

Eric Wieser (Oct 15 2025 at 16:40):

Admittedly seems very marginal

Thomas Murrills (Oct 15 2025 at 16:42):

(I’ll also link the thread #lean4 > Alternative and do-notation as well as #lean4 > Applicative and do-notation here for good measure)


Last updated: Dec 20 2025 at 21:32 UTC