Skip to content

Instantly share code, notes, and snippets.

@logaan
Created July 24, 2019 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save logaan/9e1c958b87506d11868107a32eef1baf to your computer and use it in GitHub Desktop.
Save logaan/9e1c958b87506d11868107a32eef1baf to your computer and use it in GitHub Desktop.
/* Here's the same function written three different ways */
/* map */
let squareMap = ns => List.map(n => n * n, ns);
// squareMap([1,2,3]) => [1, 4, 9]
/* tail recursive */
let rec squareRec' = (out, ns) =>
switch (ns) {
| [] => out
| [h, ...t] => squareRec'([h * h, ...out], t)
};
let squareRec = ns => squareRec'([], ns);
/* stepping fn */
type stepIn =
| Start(list(int))
| DoThese(list(int), list(int));
type stepOut =
| DidThese(list(int), list(int))
| Done(list(int));
let squareStep = input =>
switch (input) {
| Start(ns) => DidThese([], ns)
| DoThese(out, []) => Done(out)
| DoThese(out, [h, ...t]) => DidThese([h * h, ...out], t)
};
let rec square' = output =>
switch (output) {
| DidThese(a, b) => square'(squareStep(DoThese(a, b)))
| Done(ns) => ns
};
let square = ns => square'(squareStep(Start(ns)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment