3

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))
program.exe
  • 451
  • 4
  • 12
tDownUnder
  • 149
  • 6
  • You shouldn't use the same variable name for different variables in the same declaration as you do here: `c >>= ...` and `(c, st3) = ...` – md2perpe Mar 26 '21 at 20:37
  • @md2perpe oh wait is that because i use c in my bind function so on the next line i should use something else yeah? `(>>=) :: ST b -> (b -> ST c) -> ST c` – tDownUnder Mar 26 '21 at 20:43
  • The `c` in the line `(>>=) :: ST b -> (b -> ST c) -> ST c` does not conflict with the `c` in `c >>= ...` or with that in `(c, st3) = ...`, because in the first case it's a *type variable* while in the latter case it's an ordinary (value) variable. What I referred to was that you have one `c` to the left of `>>=` and then introduce another `c` in `(c, st3) = ...`. Rename the latter one to `t''`. – md2perpe Mar 26 '21 at 20:48
  • `Monad` and others can be [derived `via`](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/deriving_via.html?highlight=derivingvia#extension-DerivingVia) [`State Int`](http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Lazy.html#t:State): `newtype ST b = S (Int -> (b, Int)) deriving (Functor, Applicative, Monad, MonadFix) via State Int` – Iceland_jack Mar 26 '21 at 21:33

1 Answers1

1

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.

md2perpe
  • 3,372
  • 2
  • 18
  • 22