Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are monad laws enforced in Haskell?

Tags:

haskell

monads

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
  (>>=) :: m a -> (a -> m b) -> m b
  (>>) :: m a -> m b -> m b
  return :: a -> m a
  fail :: String -> m a

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

return a >>= k  =  k a
m >>= return  =  m
m >>= (\x -> k x >>= 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"?

like image 290
George Avatar asked May 09 '16 20:05

George


People also ask

How do monads work Haskell?

A monad is an algebraic structure in category theory, and in Haskell it is used to describe computations as sequences of steps, and to handle side effects such as state and IO. Monads are abstract, and they have many useful concrete instances. Monads provide a way to structure a program.

Is list a monad Haskell?

Lists are a fundamental part of Haskell, and we've used them extensively before getting to this chapter. The novel insight is that the list type is a monad too! As monads, lists are used to model nondeterministic computations which may return an arbitrary number of results.

What does bind do in Haskell?

So, the Haskell bind takes a value enclosed in a monad, and returns a function, which takes a function and then calls it with the extracted value.

What are the monad laws?

A proper monad must satisfy the three monad laws: left identity, right identity, and associativity. Together, left identity and right identity are know as simply identity.


2 Answers

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
like image 146
Cirdec Avatar answered Oct 14 '22 10:10

Cirdec


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.

like image 38
Free_D Avatar answered Oct 14 '22 08:10

Free_D