Created
July 24, 2019 10:49
-
-
Save logaan/9e1c958b87506d11868107a32eef1baf to your computer and use it in GitHub Desktop.
This file contains 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
/* 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