defination and laws of monad in haskell

Functor

Defination

class Functor f where
    fmap :: (a -> b) -> f a -> f b

Laws

  1. fmap id = id
  2. fmap (g . h) = fmap g . fmap h

Applicative

Defination

class Functor f => Applicative f where
    pure :: a -> f a
    (<*>) :: f (a -> b) -> f a -> f b

Laws

  1. pure id <*> x = x
  2. pure (g x) = pure g <*> pure x
  3. x <*> pure y = pure (\g -> g y) <*> x
  4. x <*> (y <*> z) = (pure (.) <*> x <*> y ) <*> z

Monad

Defination

class Applicative m => Monad m where
    return :: a -> m a
    (>>=) :: m a -> (a -> m b) -> m b
    
    return = pure

Laws

  1. return x >>= f = f x
  2. mx >>= return = mx
  3. (mx >>= f) >>= g = mx >>= (\x -> (f x >>= g))

Alternative

Defination

class Applicative f => Alternative f where
    empty :: f a
    (<|>) :: f a -> f a -> f a

Laws

  1. empty <|> x = x
  2. x <|> empty = x
  3. x <|> (y <|> z) = (x <|> y) <|> z
点我阅读更多...