Created
March 1, 2018 11:30
-
-
Save tfc/94f9d01f0fc35d5ed8dadb009b09b2c4 to your computer and use it in GitHub Desktop.
Demonstration of a traffic light with state in haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env stack | |
-- stack --resolver lts-10.7 --install-ghc runghc | |
import Control.Concurrent (threadDelay) | |
import Control.Monad.State | |
data TrafficLightColor = Red | Yellow | Green deriving Show | |
type TrafficLightState = (TrafficLightColor, Int) | |
nextColorRule :: TrafficLightColor -> TrafficLightState | |
nextColorRule Red = (Yellow, 3) | |
nextColorRule Yellow = (Green, 10) | |
nextColorRule Green = (Red, 20) | |
nextColor :: TrafficLightState -> TrafficLightState | |
nextColor (c, 0) = nextColorRule c | |
nextColor (c, t) = (c, t - 1) | |
type TrafficLightStateMonad a = StateT TrafficLightState IO a | |
runTrafficLight :: TrafficLightStateMonad () | |
runTrafficLight = modify nextColor | |
printTrafficLight :: TrafficLightStateMonad () | |
printTrafficLight = liftIO . print =<< get | |
main = runStateT foreverTraffic initialState | |
where | |
waitASecond = liftIO $ threadDelay $ (10^6) | |
foreverTraffic = forever $ runTrafficLight >> printTrafficLight >> waitASecond | |
initialState = nextColorRule Green |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment