Last active
May 2, 2018 13:12
-
-
Save masaeedu/5d6c75e3a2f7668734fc1ee8e2909962 to your computer and use it in GitHub Desktop.
Datatype-generic lists
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
| const Arr = (() => { | |
| const Nil = []; | |
| const Cons = head => rest => [head, ...rest]; | |
| const match = ({ Cons, Nil }) => a => | |
| a.length === 0 ? Nil : Cons(a[0])(a.slice(1)); | |
| return { Nil, Cons, match }; | |
| })(); | |
| const GenericList = ({ Cons, Nil, match }) => { | |
| // Misc | |
| const length = match({ Nil: 0, Cons: _ => rest => 1 + length(rest) }); | |
| // Functor | |
| const map = f => | |
| match({ Nil, Cons: head => rest => Cons(f(head))(map(f)(rest)) }); | |
| return { length, map }; | |
| }; | |
| console.log(GenericList(Arr).length([0, 1, 2])); | |
| // 3 | |
| console.log(GenericList(Arr).map(x => x * 2)([1, 2, 3])); | |
| // [2, 4, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment