I am experimenting with the functional List
type and structural sharing. Since Javascript doesn't have a Tail Recursive Modulo Cons optimization, we can't just write List
combinators like this, because they are not stack safe:
const list =
[1, [2, [3, [4, [5, []]]]]];
const take = n => ([head, tail]) =>
n === 0 ? []
: head === undefined ? []
: [head, take(n - 1) (tail)];
console.log(
take(3) (list) // [1, [2, [3, []]]]
);
Now I tried to implement take
tail recursively, so that I can either rely on TCO (still an unsettled Promise
in Ecmascript) or use a trampoline (omitted in the example to keep things simple):
const list =
[1, [2, [3, [4, [5, []]]]]];
const safeTake = n => list => {
const aux = (n, acc, [head, tail]) => n === 0 ? acc
: head === undefined ? acc
: aux(n - 1, [head, acc], tail);
return aux(n, [], list);
};
console.log(
safeTake(3) (list) // [3, [2, [1, []]]]
);
This works but the new created list is in reverse order. How can I solve this issue in a purely functional manner?