Reputation: 432
I am very new to monads within haskell and i am trying to develop my knowledge with monads ny creating some instances but I am really quite confused with this one i am getting a few errors and have been at it for a bit as i am still unsure any help and explanations are appreciated this is what i have so far, any ideas where i am going wrong?
newtype ST b = S (Int -> (b, Int))
runState :: ST b -> Int -> (b, Int)
runState (S b) st = b st
instance Monad ST where
return :: b -> ST b
return x = S (\st -> (x, st)) the new state with a b
(>>=) :: ST b -> (b -> ST c) -> ST c
c >>= c' = S (\st1 ->
let (b, st2) = runState c st1
(c, st3) = runState (c' b) st2
in (c, st3))
Upvotes: 1
Views: 657
Reputation: 3081
You might have to give implementations for Applicative and Functor as well:
import Control.Applicative
import Control.Monad (liftM, ap)
newtype ST b = S (Int -> (b, Int))
runState :: ST b -> Int -> (b, Int)
runState (S b) st = b st
instance Monad ST where
-- return :: b -> ST b
return x = S (\st -> (x, st)) -- takes in the current state and returns the new state with a b
-- (>>=) :: ST b -> (b -> ST c) -> ST c
c >>= c' = S (\st1 ->
let (b, st2) = runState c st1
(c'', st3) = runState (c' b) st2
in (c'', st3))
instance Applicative ST where
pure = return
(<*>) = ap
instance Functor ST where
fmap = liftM
I found that here.
Upvotes: 1