Created
September 2, 2019 01:58
-
-
Save gaku-sei/c304134b0a008c038167a4769bf8e3cc to your computer and use it in GitHub Desktop.
Nonempty lists with clean syntax in Reason (requires Bucklescript 6.*)
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
type empty; | |
type nonempty; | |
type t(_, _) = | |
| []: t('a, empty) | |
| ::('a, t('a, _)): t('a, nonempty); | |
let rec fromList: ('a, list('a)) => t('a, nonempty) = | |
x => | |
fun | |
| [] => [x] | |
| [head, ...rest] => [x, ...fromList(head, rest)]; | |
let rec toList: type a. ('b, t('b, a)) => list('b) = | |
x => | |
fun | |
| [] => [] | |
| [x] => [x] | |
| [head, ...rest] => [x, ...toList(head, rest)]; | |
let rec map: type a. (t('b, a), 'b => 'c) => t('c, a) = | |
fun | |
| [] => (_ => []) | |
| [head, ...tail] => (f => [f(head), ...map(tail, f)]); | |
let head: t('a, nonempty) => 'a = | |
fun | |
| [head, ..._] => head; | |
[1]->head->Js.log; // Compiles and works as expected, notice that an int is returned, not an option(int) | |
// []->head->Js.log; // Doesn't even compile! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment