Created
June 15, 2012 20:10
-
-
Save uday-rayala/2938479 to your computer and use it in GitHub Desktop.
Mars rover 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
data Position = Position Int Int Direction | |
deriving (Show, Eq, Read) | |
data Direction = N | E | W | S | |
deriving (Show, Eq, Enum, Bounded, Read) | |
data Command = L | R | M | |
deriving (Show, Eq, Enum, Bounded, Read) | |
data DeltaPosition = DeltaPosition Int Int | |
data State = State { | |
leftDirection :: Direction, | |
rightDirection :: Direction, | |
delta :: DeltaPosition | |
} | |
toPosition input = (read ("Position " ++ input)) :: Position | |
toCommands input = map (\i -> (read [i]) :: Command) input | |
state N = (State W E (DeltaPosition 0 (-1))) | |
state W = (State S N (DeltaPosition (-1) 0)) | |
state S = (State E W (DeltaPosition 0 1)) | |
state E = (State N S (DeltaPosition 1 0)) | |
add (Position x y d) (DeltaPosition x' y') = Position (x + x') (y + y') d | |
execute (Position x y d) L = Position x y (leftDirection (state d)) | |
execute (Position x y d) R = Position x y (rightDirection (state d)) | |
execute p@(Position x y d) M = add p (delta (state d)) | |
route position commands = foldl execute (toPosition position) (toCommands commands) | |
-- route "1 2 N" "LRLRM" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment