2 ms·
An infinite list has a length, it just happens to be (countable) infinite. Of course, as JS doesn't do (guaranteed) tail call optimisation, even finite lists w
by ReleaseCandidat 3y ago
An infinite list has a length, it just happens to be (countable) infinite.
Of course, as JS doesn't do (guaranteed) tail call optimisation, even finite lists will have "no length" ;)
(and first rewriting `length` to be tail recursive (or using a loop with mutation):
function length(l) {
function go(l, acc) {
if (l == null) {
return acc;
} else {
return go(l.rest, acc + 1);
}
}
return go(l, 0);
}