【发布时间】:2011-06-12 23:16:46
【问题描述】:
我正在尝试在 Haskell 中使用 monads 做一个全局计数器,我想每次使用 monad 计数器时都获得递增的值,但是每次都获得相同的值时我有点卡住了! 代码清单如下:
module CounterMonad where
data Counter a = C (Int -> (Int, a))
--reset the counter
new :: Counter ()
new = C $ \_ -> (0, ())
-- increment the counter:
--inc :: Counter Int
--inc = C $ \n -> (n+1, n)
inc = get >>= \s -> (put (s+1))
-- returning the current value of the counter
get :: Counter Int
get = C $ \n -> (n, n)
--
put x = C $ \n -> (x, x)
--return is nop, >>= is sequential exectuion
instance Monad Counter where
return r = C $ \n -> (n, r)
(>>=) (C f) g = C $ \n0 -> let (n1, r1) = f n0
C g' = g r1
in g' n1
run :: Counter a -> a
run (C f) = snd (f 0)
tickC = do
inc
c <- get
return c
当我尝试以run tickC 执行时,它总是返回 1。
我想要的是每次我run tickC 时,它都会返回递增的值,例如 1, ,2, 3,4 ....
我知道那里肯定有一些愚蠢的问题,你们能指出是怎么回事吗?
【问题讨论】: