Skip to content

Instantly share code, notes, and snippets.

@christian-marie
Created March 26, 2015 01:23
Show Gist options
  • Save christian-marie/a92a26608599ae74adf4 to your computer and use it in GitHub Desktop.
Save christian-marie/a92a26608599ae74adf4 to your computer and use it in GitHub Desktop.
GADTs for simple protocol
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S
-- States
data Listening
data Disconnected
data Ready
data Closing
data Protocol start end where
Accept :: Protocol Ready Closing -> Protocol Listening Disconnected
Send :: ByteString -> Protocol Ready x -> Protocol Ready x
Recv :: (ByteString -> Protocol Ready x) -> Protocol Ready x
Close :: Protocol Ready Closing
proto :: Protocol Listening Disconnected
proto = Accept $ Send "Hi." $ Recv (\x -> if x == "Hi." then Close else Send "Jerk." Close)
interpIO :: Protocol start end -> IO ()
interpIO (Accept k) = S.putStrLn "Connected" >> interpIO k
interpIO (Send payload k) = S.putStrLn payload >> interpIO k
interpIO (Recv k) = S.getLine >>= interpIO . k
interpIO Close = S.putStrLn "Disconnected"
main :: IO ()
main = interpIO proto
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment