使用periodic`的`考慮下面的代碼:在NetWire 5
-- 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上是允許的,比把答案放在問題上更有意義。另外,除非你想強調它們之間的一些區別,否則可能不需要複製我的答案。 – Cubic 2015-03-03 16:50:18