给出以下代码;它基本上是一个包含一堆数字和操作(不包括操作代码)的计算器,并通过改变状态来评估堆栈。
data InternalState = InternalState
{ stack :: [Double]
, memory :: Double
}
type CalcState = State InternalState
type Calculation = CalcState ()
pop :: CalcState Double
pop = state $ \st -> case stack st of
[] -> (0.0,st)
x:xs -> (x,st { stack = xs })
push :: Double -> CalcState ()
push d = modify $ \st -> st { stack = d : stack st }
我想实现一个函数recall :: Calculation
和store :: Calculation
,这样,给定一堆数字,store
取最顶层的数字并记住它(将InternalState更改为{{ 1}}等于该顶部数字。memory
应将单个存储的数字推送到数字堆栈的顶部。
我的问题是,我不知道应该如何使用recall
,get
等状态函数来适当地修改状态。我可以看到我想要改变状态,以便只改变内存(对于put
类型的所有其他操作,内存保持0.0)。我开始使用
Calculation
store
因为我知道我必须把最高值放在堆栈上,但我不知道如何使用这个值来改变状态的内存。
答案 0 :(得分:1)
recall = do
x <- gets memory
modify (\s -> InternalState (x : stack s) x)
store = do
(x:xs) <- gets stack
put $ InternalState xs x