使用状态在计算器上实现 Store/Recall 功能

Implementing Store/Recall Features on Calculator Using State

给出以下代码;它基本上是一个计算器,包含一堆数字和操作(不包括操作代码)并通过状态更改对堆栈求值。

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 :: Calculationstore :: Calculation,这样,给定一堆数字,store 取最上面的数字并记住它(将 InternalState 更改为memory 等于顶部数字。recall 应该将单个存储的数字推到数字堆栈的顶部。

我的问题是,我不知道应该如何使用 getput 等状态函数来适当地修改状态。我可以看到我想要更改状态以便仅更改内存(否则对于类型 Calculation 的所有其他操作,内存保持 0.0)。我开始用

实现 store
store = do
   x <- pop
   push x

因为我知道我必须获取并放回堆栈的顶部值,但我不知道如何使用该值来仅更改状态的内存。

recall = do
  x <- gets memory
  modify (\s -> InternalState (x : stack s) x)

store = do
  (x:xs) <- gets stack
  put $ InternalState xs x