Skip to content

Instantly share code, notes, and snippets.

@reidev275
Created September 1, 2020 01:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reidev275/0208fb00f0259a6da78f304e2b236555 to your computer and use it in GitHub Desktop.
Save reidev275/0208fb00f0259a6da78f304e2b236555 to your computer and use it in GitHub Desktop.
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