Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample solution of Mars Rover kata
import Html exposing (div, button, text, h3, h2, input)
import Html.Events exposing (onClick, onInput)
import Html.Attributes exposing(..)
type Direction = North | South | East | West
type alias Location =
{ x: Int
, y: Int
}
type alias Model =
{ location: Location
, direction: Direction
}
main =
Html.beginnerProgram
{ model = {location={x=0, y=0}, direction=North}
, view = view
, update = update
}
view model =
div []
[ button [ onClick MoveForward ] [ text "Forward" ]
, button [ onClick MoveBackward ] [ text "Backward" ]
, button [ onClick TurnLeft] [text "Rotate Left"]
, button [ onClick TurnRight] [text "Rotate Right"]
, div []
[ h2 [] [text ("Location: " ++ (printLocation model.location))]
, h2 [] [text ("Direction: " ++ (toString model.direction))]
]
]
printLocation location =
toString(location.x) ++ "," ++ toString(location.y)
type Msg = MoveForward | MoveBackward | TurnLeft | TurnRight
update msg model =
case msg of
MoveForward ->
{model | location=moveForward model.direction model.location}
MoveBackward ->
{model | location=moveBackward model.direction model.location}
TurnLeft ->
{model | direction=turnLeft model.direction}
TurnRight ->
{model | direction=turnRight model.direction}
moveForward direction location =
case direction of
North -> {location | y=location.y+1}
South -> {location | y=location.y-1}
East -> {location | x=location.x+1}
West -> {location | x=location.x-1}
moveBackward direction location =
case direction of
North -> moveForward South location
South -> moveForward North location
East -> moveForward West location
West -> moveForward East location
turnLeft direction =
case direction of
North -> West
West -> South
South -> East
East -> North
turnRight direction =
direction
|> turnLeft
|> turnLeft
|> turnLeft
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.