我有这个
newtype State' s a = State' { runState' :: (s, Counts) -> (a, s, Counts) }
现在我想要写一个函数。
getCounts :: State' s a -> Counts
有没有任何方法可以实现这个目标?
getCounts :: State' s Counts
getCounts = State' (\ (s,c) -> (c,s,c))
然后你可以在计算中使用它:
myStateComp = do
-- whaever
counts <- getCounts
-- ...
是的,你也可以对它进行eval
操作。
假设你的evalState'
长这样:
evalState' :: State' s a -> s -> Counts -> a
evalState' st initState initCounts =
let (a,_,_) = runState st (initState,initCounts)
in a
evalState' getCounts initState initCount
initCount
返回 - 但没有任何其他计算,我看不出还能回答什么其他问题。myComp = do
-- ... do comp
getCounts
然后
evalState' myComp initState initCount
运行任何计算并返回最后一个计数
@bheklilr 暗示的替代方案是使用
import Control.Monad.State
type State' s a = State (s, Counts) a
并且:
myStateComp = do
-- whaever
(state,counts) <- get
-- ...
因此你的getCounts
实际上就是fmap snd get
getCounts :: State' s Counts
?(在运行状态计算之前,你不可能知道计数 - 所以你可能想从状态内部查询计数?) - Random DevgetCounts :: State' s Counts
。 - bheklilrgetCounts = State' (\ (s,c) -> (c,s,c))
怎么样? - Random DevState
不是来自于Control.Monad.State
吗?你可以看一下这个monad中get
的实现方式,或许能够得到一些启示。 - bheklilrCounts
,那么Counts
是什么并不重要 - 它实际上只是另一个s
(我认为这也是 bheklilr 想说的)。 - Random Dev