Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any interesting commutative monads in Haskell?

Tags:

haskell

monads

Until I edited it today, the Haskell Wiki claimed that Maybe is a commutative monad (actually, I think it still claims it somewhere). This is clearly wrong, because

do {a <- Nothing; b <- undefined; return (a,b)} === Nothing

while

do {b <- undefined; a <- Nothing; return (a,b)} === undefined

This failure of commutativity is actually rather important in real code: programmers rely on the fact that the computation will stop as soon as it reaches Nothing.

This leaves (among the monads described as commutative on the Haskell Wiki) only the Reader monad, which doesn't seem to do anything terribly exciting. That raised the question in my mind about whether there are any commutative monads in Haskell that are substantially different from Reader, aside from restrictions of Reader.

Edit

I just realized it's also possible to make a restricted Writer monad be commutative—it needs to accumulate values in some commutative monoid. Still not interesting.

like image 207
dfeuer Avatar asked Jan 10 '23 08:01

dfeuer


2 Answers

Statements like that sometimes have an implied "ignoring bottoms" requirement and this is probably one of those cases. It's commutative if we ignore bottoms. It's better to explicitly express that requirement though, because it can become important.

If we do ignore bottoms, then Maybe is a commutative Monad as well. Of course, as you mentioned in the question, bottoms are important to consider practically speaking, so it is good to be aware of the non-commutativity in their presence.

like image 52
David Young Avatar answered Jan 19 '23 01:01

David Young


The set monad qualifies as commutative and, IMO, interesting.

like image 35
leftaroundabout Avatar answered Jan 19 '23 01:01

leftaroundabout