简体   繁体   中英

Are monad laws enforced in Haskell?

From the Haskell wiki:

Monads can be viewed as a standard programming interface to various data or control structures, which is captured by the Monad class. All common monads are members of it:

 class Monad m where (>>=) :: ma -> (a -> mb) -> mb (>>) :: ma -> mb -> mb return :: a -> ma fail :: String -> ma 

In addition to implementing the class functions, all instances of Monad should obey the following equations, or Monad Laws:

 return a >>= k = ka m >>= return = m m >>= (\\x -> kx >>= h) = (m >>= k) >>= h 

Question: Are the three monad laws at the bottom actually enforced in any way by the language? Or are they extra axioms that you must enforce in order for your language construct of a "Monad" to match the mathematical concept of a "Monad"?

You are responsible for enforcing that a Monad instance obeys the monad laws. Here's a simple example that doesn't .

Even though its type is compatible with the Monad methods, counting the number of times the bind operator has been used isn't a Monad because it violates the law m >>= return = m

{-# Language DeriveFunctor #-}

import Control.Monad

data Count a = Count Int a
    deriving (Functor, Show)

instance Applicative Count where
    pure = return
    (<*>) = ap

instance Monad Count where
    return = Count 0
    (Count c0 a) >>= k = 
        case k a of
            Count c1 b -> Count (c0 + c1 + 1) b

No, the monad laws are not enforced by the language. But if you don't adhere to them, your code may not necessarily behave as you'd expect in some situations. And it would certainly be confusing to users of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM