Skip to content

Instantly share code, notes, and snippets.

@masaeedu
Last active May 2, 2018 13:12
Show Gist options
  • Save masaeedu/5d6c75e3a2f7668734fc1ee8e2909962 to your computer and use it in GitHub Desktop.
Save masaeedu/5d6c75e3a2f7668734fc1ee8e2909962 to your computer and use it in GitHub Desktop.
Datatype-generic lists
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