Skip to content

Instantly share code, notes, and snippets.

@jalehman
Last active October 11, 2015 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jalehman/243237a52d72aa5d545e to your computer and use it in GitHub Desktop.
Save jalehman/243237a52d72aa5d545e to your computer and use it in GitHub Desktop.
Various implementations of `map` using recursion.
function first(xs) {
return xs[0];
};
function rest(xs) {
if (xs.length <= 0) {
return [];
}
return xs.slice(1, xs.length);
};
function conj(xs, x) {
var t = xs;
t.push(x);
return t;
};
function cons(x, xs) {
var t = xs;
t.unshift(x);
return t;
}
function map(xs, f) {
if (xs.length <= 0) {
return [];
}
return cons(f(first(xs)), map(rest(xs), f));
};
// OR:
function map_ternary(xs, f) {
return xs.length <= 0 ? [] : cons(f(first(xs)), map_ternary(rest(xs), f));
}
// NOTE: This doesn't work in JS no TCO -- see https://en.wikipedia.org/wiki/Tail_call
function map_iter(xs, f) {
function iter(xs, f, acc) {
if (xs.length <= 0) {
return [];
}
return iter(rest(xs), f, conj(acc, f(first(xs))));
};
return iter(xs, f, []);
}
function inc(x) { return x + 1; };
map([1,2,3,4], inc);
map_iter([1,2,3,4], inc);
map_ternary([1,2,3,4], inc);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment