考虑以下代码:
-- 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)
但是,最终结果与我的第一次尝试完全一样。我在这里想念什么?
编辑:请参阅此答案以获取已接受答案的(劣质)替代方案。