-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfivemonads.hs
More file actions
42 lines (30 loc) · 1.05 KB
/
Copy pathfivemonads.hs
File metadata and controls
42 lines (30 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
{-# LANGUAGE NoImplicitPrelude #-}
module Monads where
import Prelude hiding (Monad, Identity, Maybe(..), State, Reader, Writer)
import Data.Monoid
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
data Identity a = Identity a
deriving (Show, Eq)
data Maybe a = Nothing | Just a
deriving (Show, Eq)
data State s a = State {runState :: s -> (a, s)}
data Reader s a = Reader {runReader :: s -> a }
data Writer w a = Writer {runWriter :: (w, a)}
instance Monad Identity where
return = Identity
(Identity v) >>= f = f v
instance Monad Maybe where
return = Just
Nothing >>= _ = Nothing
(Just v) >>= f = f v
instance Monad (State s) where
return v = State (\s -> (v, s))
(State g) >>= f = State (\s -> let (a, s') = g s in runState (f a) s')
instance Monad (Reader s) where
return v = Reader (\_ -> v)
(Reader g) >>= f = Reader (\s -> let a = g s in runReader (f a) s)
instance Monoid w => Monad (Writer w) where
return v = Writer (mempty, v)
(Writer (s, v)) >>= f = let (w, a) = runWriter (f v) in Writer (s <> w, a)