|
|
|
|
|
by mcaruso
2079 days ago
|
|
Let's take a look at how we might write a function like `map` the (pure) functional way in a language like JS: const head = ([x, ...xs]) => x;
const tail = ([x, ...xs]) => xs;
const map = (list, fn) => {
if (list.length === 0) {
return [];
} else {
return [fn(head(list)), ...map(tail(list), fn)];
}
};
map([1, 2, 3], x => x + 1); // [2, 3, 4]
We're not keeping track of any state here. Using recursion you don't need to keep track of the current element in the list for example (when you run this on a physical machine it will of course, but not at the conceptual level). |
|