State Monads - In Haskell

I’m trying to create a calculator with an integer state which allows the user to update this state using commands. This is what I’ve got so far.

{-# LANGUAGE FlexibleContexts #-}
import Control.Monad.Except
import Control.Monad.State


data CalcCmd = EnterC
         | StoreC Int CalcCmd
         | AddC Int CalcCmd
         | MultC Int CalcCmd
         | DivC Int CalcCmd
         | SubC Int CalcCmd


run :: (MonadState Int m, MonadError String m) => CalcCmd -> m ()
run (EnterC) = return()

run (StoreC a b) = do
                  put (a)
                  run b

run (AddC a b) = do
                modify((+) a)
                run b

run (MultC a b) = do
                modify((*) a)
                run b

run (DivC a b) = do
                modify ((div) a)
                run b

run (SubC a b) = do
                modify((-) a)
                run b

No matter what the commands are, the state always ends up as 0. For example, Both “StoreC 7 (EnterC)” and “StoreC 7 (AddC 14 (DivC 3 EnterC))” give the state back as 0. What am I doing wrong?

The textbook says The StoreC command should manually update the state And the EnterC command should terminate the calculation, returning the unit type.

Also When using state monads, is there a few things which I should be doing no matter what the function is about?

Can you share the full command you use to run the examples? This works for me:

ghci> runStateT (run (StoreC 7 EnterC)) 0 :: Either String ((), Int)
Right ((),7)

Oh, I do see a problem with DivC: you have div the wrong way around. It should be: modify (\x -> div x a) or modify (`div` a).

I see the question also has an answer and a bunch of comments on stack overflow: