Skip to content

Instantly share code, notes, and snippets.

@jhickner
Created March 7, 2013 00:03
Show Gist options
  • Save jhickner/5104380 to your computer and use it in GitHub Desktop.
Save jhickner/5104380 to your computer and use it in GitHub Desktop.
import Control.Monad
import Control.Applicative
import Control.Proxy
import qualified Control.Proxy.Trans.State as S
import System.IO
import Prelude hiding (Left, Right)
type Pos = (Int, Int)
data Input = Up | Down | Left | Right | Invalid deriving Show
toInput :: Char -> Input
toInput c = case c of
'u' -> Up
'd' -> Down
'l' -> Left
'r' -> Right
_ -> Invalid
move :: Input -> Pos -> Pos
move i p@(x,y) = case i of
Up -> (x,y-1)
Down -> (x,y+1)
Left -> (x-1,y)
Right -> (x+1,y)
Invalid -> p
inputs :: Proxy p => () -> Producer p Input IO ()
inputs () = runIdentityP . forever $ lift (toInput <$> getChar) >>= respond
-- embed some local state into this proxy that will hold the current Pos
-- and accept an initial position as an arg
moves :: (Monad m, Proxy p) => Pos -> () -> Pipe p Input Pos m ()
moves p () = S.evalStateP p $ forever $ do
s <- move <$> request () <*> S.get
S.put s
respond s
main = do
hSetEcho stdin False
runProxy $ inputs >-> moves (0, 0) >-> printD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment