I am attempting to write some stateful code in Haskell. To this end, I follow this material. At this point, I got my way to monads and functors, and, roughly put, I am confused and can’t make progress with the material. I have this M(Non)WE:
import Control.Monad
data State s a = State (s -> (a,s))
runState (State f) s = f s
put :: s -> State s ()
put state = State (oldState -> ((), state))
get :: State s s
get = State (state -> (state,state))
modify :: (s -> s) -> State s ()
modify f = State (state -> ((), f state))
-- The following 3 rows fail:
instance Functor State where
fmap f (State s) = State (f x)
-- The following 3 rows fail:
instance Applicative State where
pure = return
(<*>) = ap
instance Monad (State s) where
return x = State (s -> (x,s))
op >>= f = State h
where h state0 = let (val,state1) = runState op state0
op2 = f val
in runState op2 state1
add :: Int -> State Int ()
add i = do old <- get
put (old+i)
main = do
print(runState (add 1 >> add 3 >> add 5 >> add 6) 0)
The error message is:
question1.hs:16:18: error:
* Expecting one more argument to `State'
Expected kind `* -> *', but `State' has kind `* -> * -> *'
* In the first argument of `Functor', namely `State'
In the instance declaration for `Functor State'
|
16 | instance Functor State where
| ^^^^^
question1.hs:19:22: error:
* Expecting one more argument to `State'
Expected kind `* -> *', but `State' has kind `* -> * -> *'
* In the first argument of `Applicative', namely `State'
In the instance declaration for `Applicative State'
|
19 | instance Applicative State where
^^^^^
What am I missing here?
PS. (I am a beginner Haskell programmer. Please bear with me.)
1