Skip to content

Instantly share code, notes, and snippets.

@bluurn
Created January 29, 2019 14:29
Show Gist options
  • Save bluurn/e8f03ebcd05faabbd4761176bf752c94 to your computer and use it in GitHub Desktop.
Save bluurn/e8f03ebcd05faabbd4761176bf752c94 to your computer and use it in GitHub Desktop.
JS: List Implementation
const cons = (x, y) => f => f(x, y);
const car = f => f((x, y) => x);
const cdr = f => f((x, y) => y);
function list() {
const h = Array.prototype.slice.call(arguments, 0)[0];
const t = Array.prototype.slice.call(arguments, 1);
if (h == null) {
return cons(null, null);
}
return cons(h, list.apply(this, t));
}
const head = lst => car(lst);
const tail = lst => cdr(lst);
const isEmpty = lst => head(lst) == null;
const map = (lst, fn) =>
isEmpty(lst) ?
list() :
cons(fn(head(lst)),
map(tail(lst), fn));
const reduce = (lst, acc, fn) => {
const iter = (items, result) => {
if (isEmpty(items)) {
return result;
}
return iter(tail(items), fn(head(items), result));
};
return iter(lst, acc);
};
const toString = lst =>
reduce(lst,
null,
(it, acc) =>
(acc == null ? '' : acc + ', ') + it);
const toArray = lst =>
reduce(lst,
[],
(it, acc) => acc.concat(it));
const reverse = lst =>
reduce(lst,
list(),
(it, acc) => cons(it, acc));
const lst = list(1,2,3,4,5,6);
console.log(toString(map(lst, x => x * 3)));
console.log(reduce(lst, 0, (it, acc) => acc + it));
console.log(toString(lst));
console.log(toArray(reverse(lst)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment