[英]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.我正在尝试使用 integer state 创建一个计算器,它允许用户使用命令更新此 state。 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?无论命令是什么,state 总是以 0 结束。例如,“StoreC 7 (EnterC)”和“StoreC 7 (AddC 14 (DivC 3 EnterC))”都将 state 返回为 0。我是什么做错了吗?
The textbook says The StoreC command should manually update the state And the EnterC command should terminate the calculation, returning the unit type.教科书说 StoreC 命令应该手动更新 state 而 EnterC 命令应该终止计算,返回单位类型。
Also When using state monads, is there a few things which I should be doing no matter what the function is about?另外,当使用 state monads 时,无论 function 是什么,我都应该做一些事情吗?
Could not reproduce.无法重现。
runStateT (run cmd3:: CS ()) (0:: Int)
returns Right ((), 7)
here. runStateT (run cmd3:: CS ()) (0:: Int)
在这里返回Right ((), 7)
。 (The others do return 0
, because div 3 ((+) 14 7) = div 3 21 = 0
and div 0 ((*) 2 10) = div 0 20 = 0
. In other words, your State
monad is doing the calculation you asked it to do, so your misunderstanding, whatever it is, probably is not related to state monads.) (其他人确实返回
0
,因为div 3 ((+) 14 7) = div 3 21 = 0
和div 0 ((*) 2 10) = div 0 20 = 0
。换句话说,你的State
monad 正在做你要求它做的计算,所以你的误解,不管它是什么,可能与 state monads 无关。)
Are you double-plus sure you are loading the file you saved?你确定你正在加载你保存的文件吗? Is it possible you're saving to a different directory than you are loading from, eg?
是否有可能你保存到一个不同于你从中加载的目录,例如? Or perhaps forgot to press save (I've seen it happen even to professionals...)?
或者可能忘记按保存(我什至见过它发生在专业人士身上......)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.