elm/exercises/robot-simulator/RobotSimulator.example.elm

99 lines
1.8 KiB
Elm
Raw Permalink Normal View History

module RobotSimulator exposing (..)
2016-03-28 10:23:01 +00:00
import String
type Bearing
= North
| East
| South
| West
2016-03-28 10:23:01 +00:00
type alias Robot =
{ bearing : Bearing
, coordinates : { x : Int, y : Int }
}
2016-03-28 10:23:01 +00:00
defaultRobot : Robot
defaultRobot =
{ bearing = North
, coordinates = { x = 0, y = 0 }
}
2016-03-28 10:23:01 +00:00
turnRight : Robot -> Robot
turnRight robot =
case robot.bearing of
North ->
{ robot | bearing = East }
2016-03-28 10:23:01 +00:00
East ->
{ robot | bearing = South }
2016-03-28 10:23:01 +00:00
South ->
{ robot | bearing = West }
2016-03-28 10:23:01 +00:00
West ->
{ robot | bearing = North }
2016-03-28 10:23:01 +00:00
turnLeft : Robot -> Robot
turnLeft robot =
case robot.bearing of
North ->
{ robot | bearing = West }
2016-03-28 10:23:01 +00:00
West ->
{ robot | bearing = South }
2016-03-28 10:23:01 +00:00
South ->
{ robot | bearing = East }
2016-03-28 10:23:01 +00:00
East ->
{ robot | bearing = North }
2016-03-28 10:23:01 +00:00
advance : Robot -> Robot
advance { bearing, coordinates } =
let
updated =
case bearing of
North ->
{ coordinates | y = coordinates.y + 1 }
2016-03-28 10:23:01 +00:00
East ->
{ coordinates | x = coordinates.x + 1 }
2016-03-28 10:23:01 +00:00
South ->
{ coordinates | y = coordinates.y - 1 }
2016-03-28 10:23:01 +00:00
West ->
{ coordinates | x = coordinates.x - 1 }
in
{ bearing = bearing, coordinates = updated }
2016-03-28 10:23:01 +00:00
simulate : String -> Robot -> Robot
simulate directions robot =
let
action direction =
case direction of
'L' ->
turnLeft
'R' ->
turnRight
'A' ->
advance
_ ->
identity
in
directions
|> String.toList
|> List.map action
|> List.foldl (\a r -> a r) robot