Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aren't Monads essentially just "conceptual" sugar?

Tags:

haskell

monads

Let's assume we allow two types of functions in Haskell:

  • strictly pure (as usual)
  • potentially non-pure (procedures)

The distinction would be made f.x. by declaring that a dot (".") as first letter of a function name declares it as a non-pure procedure.

And further we would set the rules:

  • pure functions may be called by pure and non-pure functions
  • non-pure functions may only be called by non-pure functions
  • and: non-pure functions may be programmed imperatively

With this syntactical sugar and specifications at hand - would there still be a need for Monads? Is there anything Monads could do which above rule set would not allow?

B/c as I came to understand Monads - this is exactly their purpose. Just that very smart people managed to achieve this purely by means of functional methods with a cathegory theoretical tool set at hand.

like image 726
Raffael Avatar asked Nov 28 '22 07:11

Raffael


2 Answers

No.

Monads have nothing to do with purity or impurity in principle. It just so happens that IO models impure code nicely, but Monad class can be used perfectly right for instances like State or Maybe, which are absolutely pure.

Monads also allow expressing complex context hierarchies (as I choose to call them) in a very explicit way. "pure/impure" isn't the only division you might want to make. Consider authorized/unauthorized, for example. The list of possible uses goes on and on... I'd encourage you to look at other commonly used instances, like ST, STM, RWS, "restricted IO" and friends to get a better understanding of the possibilities.

Soon enough you'll start making your own monads, tailored to the problem at hand.

like image 177
Bartek Banachewicz Avatar answered Dec 05 '22 02:12

Bartek Banachewicz


B/c as I came to understand Monads - this is exactly their purpose.

Monads in their full generality have nothing to do with purity/impurity or imperative sequencing. So no, monads are most certainly not conceptual sugar for effect encapsulation if I understood your question.

Consider that overwhelmingly most of the monads in the Prelude: List, Reader, State, Cont, Either, (->) have nothing to do with effects or IO. It's a very common misconception to assume that IO is the "canonical" monad, while in fact it's really a degenerate case.

like image 31
Stephen Diehl Avatar answered Dec 05 '22 02:12

Stephen Diehl