Skip to content

Instantly share code, notes, and snippets.

@bas080
Created October 7, 2017 21:25
Show Gist options
  • Save bas080/7ee8a937bd2b0abff06f67fc3af3fdf6 to your computer and use it in GitHub Desktop.
Save bas080/7ee8a937bd2b0abff06f67fc3af3fdf6 to your computer and use it in GitHub Desktop.
const cons = (a, b) => (
(idx) => {
if(idx === 0) {
return a;
} else if(idx === 1) {
return b;
} else {
throw "invalid index";
}
}
);
const car = (c) => c(0);
const cdr = (c) => c(1);
const isNil = (c) => car(c) === undefined && cdr(c) === undefined;
const reduce = (f, init, items) => {
const iter = (items, acc) => {
if(isNil(items)) {
return acc;
} else {
return iter(cdr(items), f(car(items), acc));
}
};
return iter(items, init);
};
const reverse = (items) => (
reduce(cons, cons(), items)
);
const list = (...items) => (
reverse(items.reduce((acc, x) => (
cons(x, acc)
), cons()))
);
const listRec = (head, ...tail) => {
return cons(
head,
tail.length === 0 ? cons() : listRec(...tail)
)
}
const listIter = (...items) => {
let ret = cons();
items.forEach(x => ret = cons(x, ret));
return ret;
};
const map = (f, items) => (
reverse(reduce((x, acc) => cons(f(x), acc), cons(), items))
);
const filter = (f, items) => (
reverse(reduce((x, acc) => f(x) ? cons(x, acc) : acc, cons(), items))
);
////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////
const inc = x => x + 1;
const even = x => x % 2 == 0;
const odd = x => x % 2 == 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment