Skip to content

Instantly share code, notes, and snippets.

@puffnfresh
Last active December 17, 2015 17:39
Show Gist options
  • Save puffnfresh/5647445 to your computer and use it in GitHub Desktop.
Save puffnfresh/5647445 to your computer and use it in GitHub Desktop.
Monad exercises
module Monads where
{- runhaskell Monads.hs -}
import Prelude hiding (Monad, (>>=), return)
{-
Laws:
* Associativity: `m >>= f >>= g` is equivalent to `m >>= \x -> f x >>= g`
* Left identity: `return a >>= f` is equivalent to `f a`
* Right identity: `m >>= return` is equivalent to `m`
-}
class Monad w where
return :: a -> w a
(>>=) :: w a -> (a -> w b) -> w b
instance Monad [] where
-- return :: a -> [a]
return a = undefined
-- (>>=) :: [a] -> (a -> [b]) -> [b]
m >>= f = undefined
instance Monad Maybe where
-- return :: a -> Maybe a
return a = undefined
-- (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
m >>= f = undefined
-- Bit trickier: a Monad for functions!
{-
instance Monad ((->) r) where
-- return :: a -> (r -> a)
return a = undefined
-- (>>=) :: (r -> a) -> (a -> (r -> b)) -> (r -> b)
m >>= f = undefined
-}
main :: IO ()
main = do
print $ [1, 2, 3] >>= (\x -> [x, x * 10, x - 1])
print $ [3, 2, 1] >>= return
print $ Just 1 >>= return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment