Last active
October 11, 2015 17:44
-
-
Save jalehman/243237a52d72aa5d545e to your computer and use it in GitHub Desktop.
Various implementations of `map` using recursion.
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
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