Created
September 1, 2020 01:50
-
-
Save reidev275/0208fb00f0259a6da78f304e2b236555 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
type heading = | |
| North | |
| South | |
| East | |
| West; | |
type position = { | |
x: int, | |
y: int, | |
heading, | |
}; | |
type dsl = | |
| Pos(position) | |
| Forward(dsl) | |
| Right(dsl); | |
// matching using switch expression | |
let rightImpl = (p: position): position => | |
switch (p.heading) { | |
| North => {...p, heading: East} | |
| East => {...p, heading: South} | |
| South => {...p, heading: West} | |
| West => {...p, heading: North} | |
}; | |
// keep the position on a 10 x 10 grid | |
let toGrid = | |
fun | |
| 0 => 10 | |
| n => n mod 10; | |
// matching using fun keyword | |
let forwardImpl = | |
fun | |
| {heading: North} as p => {...p, y: p.y + 1 |> toGrid} | |
| {heading: South} as p => {...p, y: p.y - 1 |> toGrid} | |
| {heading: East} as p => {...p, x: p.x + 1 |> toGrid} | |
| {heading: West} as p => {...p, x: p.x - 1 |> toGrid}; | |
let forward = x => Forward(x); | |
let right = x => Right(x); | |
let (>>) = (f: 'a => 'b, g: 'b => 'c, a: 'a) => g(f(a)); | |
let left = right >> right >> right; | |
let backward = right >> right >> forward >> right >> right; | |
let knight = forward >> forward >> right >> forward; | |
let rec evaluate = | |
fun | |
| Pos(p) => p | |
| Forward(d) => d |> evaluate |> forwardImpl | |
| Right(d) => d |> evaluate |> rightImpl; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment