【发布时间】:2015-05-03 08:16:16
【问题描述】:
考虑以下代码:
-- this defines what our 'state' will be
data Direction = North | East | South | West deriving (Eq, Show, Enum)
data State = State Int Bool Direction deriving (Show)
initialState :: State
initialState = State 0 True North
-- a simple routine to change a state and count the number of
-- changes
nextState :: State -> State
nextState (State i _ West) = State (i+1) False South
nextState (State i _ North) = State (i+1) True East
nextState (State i b s) = State i b $ (if b then succ else pred) s
-- a wire with local state
stateWire :: Wire s () m a State
stateWire = stateWireFrom initialState
where
stateWireFrom s = mkSFN $ \_ -> (nextState s, stateWireFrom (nextState s))
-- let's run the wire!
main = testWire clockSession_ stateWire
您可以想象,testWire 将尽可能快地运行线路并将输出打印到屏幕上。但是,如果我想每 2 秒运行一次电线怎么办?查看文档,periodic 可能是解决方案:
-- Since periodic generates events, asSoonAs is used to 'unwrap' the Event
main = testWire clockSession_ (asSoonAs . periodic 2 . stateWire)
这几乎有效。输出似乎是静态的大约 2 秒,但是当它更新时,很明显,当输出停止时,电线正在运行。也许我应该反过来做?
-- Now, this does make more sense to me...
main = testWire clockSession_ (stateWire . periodic 2)
但是,最终结果与我的第一次尝试完全一样。我在这里错过了什么?
编辑:请参阅 this answer 以获取已接受答案的(劣质)替代方案。
【问题讨论】:
-
我建议您将您的编辑作为答案发布;在 stackoverflow 上允许回答您自己的问题,并且比将答案放入问题中更有意义。另外,可能没有必要复制我的答案,除非您想强调它们之间的一些区别。