Explanation of Monad laws

前端 未结 4 1555
感动是毒
感动是毒 2021-01-30 06:46

From a gentle introduction to Haskell, there are the following monad laws. Can anyone intuitively explain what they mean?

return a >>= k             = k a
         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 07:50

    The first three laws say that "return" only wraps a value and does nothing else. So you can eliminate "return" calls without changing the semantics.

    The last law is associativity for bind. It means that you take something like:

    do
       x <- foo
       bar x
       z <- baz
    

    and turn it into

    do
       do
          x <- foo
          bar x
       z <- baz
    

    without changing the meaning. Of course you wouldn't do exactly this, but you might want to put the inner "do" clause in an "if" statement and want it to mean the same when the "if" is true.

    Sometimes monads don't exactly follow these laws, particularly when some kind of bottom value occurs. That's OK as long as its documented and is "morally correct" (i.e. the laws are followed for non-bottom values, or the results are considered equivalent in some other way).

提交回复
热议问题