 nisanth074
4/11/2015 - 9:32 AM

## Trying to solve Myntra's Challenge question to learn Haskell

Trying to solve Myntra's Challenge question to learn Haskell

``````-- Using http://www.learnyouahaskell.com/ as reference

data Coordinate = Coordinate Int Int deriving(Show, Eq)
data Direction = North | West | South | East deriving(Show, Eq)
data Position = Position Coordinate Direction deriving(Show, Eq)

instance Enum Direction where
toEnum 0 = North
toEnum 1 = East
toEnum 2 = South
toEnum 3 = West
toEnum x = toEnum (x `mod` 4)

turn (Position coordinate direction) findAdjacentDirection = Position coordinate newDirection

turnLeft position = turn position pred
turnRight position = turn position succ

moveForward (Position coordinate direction) = Position newCoordinate direction
where moveCoordinateInDirection (Coordinate x y) North = Coordinate x (y + 1)
moveCoordinateInDirection (Coordinate x y) South = Coordinate x (y - 1)
moveCoordinateInDirection (Coordinate x y) East = Coordinate (x + 1) y
moveCoordinateInDirection (Coordinate x y) West = Coordinate (x - 1) y
newCoordinate = moveCoordinateInDirection coordinate direction

startingDirection = North
startingCoordinate = Coordinate 0 0

inInitialDirection (Position _ direction) = direction == startingDirection
atStartingCoordinate (Position coordinate _) = coordinate == startingCoordinate

inFiniteCircle instructions = inFiniteCircle' instructions startingPosition
where startingPosition = Position startingCoordinate startingDirection
inFiniteCircle' instructions position
| atStartingCoordinate newPosition = True
| not (inInitialDirection newPosition) = inFiniteCircle' instructions newPosition
| otherwise = False
where newPosition = consumeInstructions instructions position

consumeInstructions "" position = position
consumeInstructions (i:is) position = consumeInstructions is newPosition
where newPosition = consumeInstruction i position

consumeInstruction 'L' position = turnLeft position
consumeInstruction 'R' position = turnRight position
consumeInstruction 'G' position = moveForward position

-- ~/tmp% ghci
-- GHCi, version 7.10.1: http://www.haskell.org/ghc/  :? for help