Created
October 9, 2020 15:48
-
-
Save rcurtis/29dff77e17a17f8af4a8342fee8ced28 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module RobotSimulator | |
open System | |
type Direction = North | East | South | West | |
type Position = int * int | |
type Robot = { direction: Direction; position: Position } | |
type Command = | |
| TurnLeft | |
| TurnRight | |
| Advance | |
let parseCmd (ch:char) : Command = | |
match Char.ToUpper ch with | |
| 'L' -> TurnLeft | |
| 'R' -> TurnRight | |
| 'A' -> Advance | |
| other -> failwith (sprintf "Unrecognized command: %A" ch) | |
let turn (cmd:Command)(direction:Direction) : Direction = | |
match (cmd, direction) with | |
| (TurnLeft, North) -> West | |
| (TurnLeft, East) -> North | |
| (TurnLeft, South) -> East | |
| (TurnLeft, West) -> South | |
| (TurnRight, North) -> East | |
| (TurnRight, East) -> South | |
| (TurnRight, South) -> West | |
| (TurnRight, West) -> North | |
| (_, _) -> failwith "Unrecognized turn" | |
let advance (pos:Position)(direction:Direction) : Position = | |
let x, y = pos | |
match direction with | |
| North -> (x, y + 1) | |
| East -> (x + 1, y) | |
| South -> (x, y - 1) | |
| West -> (x - 1, y) | |
let applyCommand (cmd:Command)(robot:Robot) : Robot = | |
match cmd with | |
| TurnLeft | TurnRight -> { robot with direction = turn cmd robot.direction } | |
| Advance -> { robot with position = advance robot.position robot.direction } | |
let create direction position = { direction = direction; position = position; } | |
let move (instructions:string) (robot:Robot) : Robot = | |
instructions | |
|> Seq.map (fun x -> parseCmd x) | |
|> Seq.fold (fun acc i -> applyCommand i acc) robot |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment