Skip to content

Instantly share code, notes, and snippets.

@uday-rayala
Created June 15, 2012 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save uday-rayala/2938479 to your computer and use it in GitHub Desktop.
Save uday-rayala/2938479 to your computer and use it in GitHub Desktop.
Mars rover in haskell
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