[Haskell-cafe] A question about "monad laws"
jonathanccast at fastmail.fm
Mon Feb 11 10:34:36 EST 2008
On 11 Feb 2008, at 5:33 AM, Deokjae Lee wrote:
> Tutorials about monad mention the "monad axioms" or "monad laws". The
> tutorial "All About Monads" says that "It is up to the programmer to
> ensure that any Monad instance he creates satisfies the monad laws".
> The following is one of the laws.
> (x >>= f) >>= g == x >>= (\v -> f v >>= g)
> However, this seems to me a kind of mathematical identity.
What do you mean by identity? It's easy enough to violate:
newtype Gen a = Gen (StdGen -> a)
runGen :: Gen a -> StdGen -> a
runGen (Gen f) = f
instance Monad Gen where
return x = Gen (const x)
a >>= f = Gen (\ r -> let (r1, r2) = split r in runGen (f (runGen
a r1)) r2) 
split returns two generators independent of each other and of its
argument; thus, this `monad' violates all *three* of the monad laws,
in the sense of equality. So, for example, the program
x <- a
denotes a random variable independent of (and hence distinct from)
a. In general, you want some kind of backstop `equality' (e.g., that
the monad laws hold in the sense of identical distribution) when you
violate them; otherwise, you will violate the expectations your users
have from the syntax of the do notation.
More information about the Haskell-Cafe