Skip to content

Instantly share code, notes, and snippets.

@tfc
Created March 1, 2018 11:30
Show Gist options
  • Save tfc/94f9d01f0fc35d5ed8dadb009b09b2c4 to your computer and use it in GitHub Desktop.
Save tfc/94f9d01f0fc35d5ed8dadb009b09b2c4 to your computer and use it in GitHub Desktop.
Demonstration of a traffic light with state in haskell
#!/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