Created
July 6, 2016 16:16
-
-
Save drwebb/96f570b6cffc8050daee3f305b1ba5bd to your computer and use it in GitHub Desktop.
Functional Kats Robot simulator kata
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
module Lib where | |
import Control.Arrow (first, second) | |
data Dir = N | E | S | W deriving (Show, Enum, Bounded) | |
type Pos = (Int, Int) | |
data Robot = Robot Dir Pos deriving Show | |
right :: Dir -> Dir | |
right W = N | |
right d = succ d | |
left :: Dir -> Dir | |
left N = W | |
left d = pred d | |
-- Dir is direction robot currently facing | |
advance :: Dir -> Pos -> Pos | |
advance N = second succ | |
advance E = first succ | |
advance S = second pred | |
advance W = first pred | |
interpretC :: Char -> Robot -> Robot | |
interpretC 'R' (Robot d p) = (Robot (right d) p) | |
interpretC 'L' (Robot d p) = (Robot (left d) p) | |
interpretC 'A' (Robot d p) = (Robot d (advance d p)) | |
interpretC _ _ = error "undefined movement command" | |
interpretS :: String -> Robot -> Robot | |
interpretS s r = foldl (flip interpretC) r s | |
test :: IO () | |
test = do | |
let r = Robot N (7,3) | |
let r' = interpretS "RAALAL" r | |
print r' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment