【问题标题】:Accessing counts in State Monad haskell在 State Monad haskell 中访问计数
【发布时间】:2014-10-14 13:13:26
【问题描述】:

我有这个

newtype State' s a = State' { runState' :: (s, Counts) -> (a, s, Counts) }

现在我想写一个函数

getCounts :: State' s a -> Counts

有什么办法可以做到吗?

【问题讨论】:

  • 我猜你想要这样的东西:getCounts :: State' s Counts? (在你运行你的状态计算之前,你不可能知道计数 - 所以你可能想从状态内部查询计数?)
  • @CarstenKönig 我认为应该是getCounts :: State' s Counts,更准确地说。
  • getCounts = State' (\ (s,c) -> (c,s,c)) 呢?
  • 不会State' s a ~ State (s, Counts) a 其中State 来自Control.Monad.State?我建议看看 get 是如何为那个 monad 实现的,以获得一些想法。
  • @dosmath 如果您只是想从该州获得它,Counts 是什么并不重要 - 它实际上只有 another s 在那里(我认为这也是 bheklilr 想说的)

标签: haskell state monads


【解决方案1】:

也许这就是你要找的东西:

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

【讨论】:

  • 好的,但是当我需要编写返回 (a,Counts) 的函数时如何使用它。如果我理解正确,现在我只能在 do 块中访问 Counts 吗?
  • 你使用初始状态的评估
  • 感谢您的回答,它有帮助!
猜你喜欢
  • 2013-05-16
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
相关资源
最近更新 更多