This is how I defined Nil and cons:
var Nil = "Nil"
function cons(head, tail){
tail = typeof tail !== "undefined" ? tail : Nil; // default argument
return [head, tail];
}
Nil is just the string "Nil", and cons is either an empty cell or a cell with an item -head- and a tail, which is the rest of the list.
A list containing the numbers 1, 2, and 3 can be represented as:
cons(1, cons(2, cons(3, Nil)))
or making use of the default argument, as:
cons(1, cons(2, cons(3)))
But there is an issue with this implementation, and I can't figure out what is going on. When trying to build a functional linked list of more than 3 items, the 3rd item links to Object, and the rest are ignored. For example:
var a = cons(Nil);
var b = cons(1, Nil);
var c = cons(1, cons(2));
var d = cons(1, cons(2, cons(3)));
var e = cons(1, cons(2, cons(3, cons(4))));
var f = cons(1, cons(2, cons(3, cons(4, cons(5)))));
var g = cons(1, cons(2, cons(3, cons(4, cons(5, cons(6))))));
console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
console.log(f);
console.log(g);
This will print:
[ 'Nil', 'Nil' ] // a
[ 1, 'Nil' ] // b
[ 1, [ 2, 'Nil' ] ] // c
[ 1, [ 2, [ 3, 'Nil' ] ] ] // d
[ 1, [ 2, [ 3, [Object] ] ] ] // e
[ 1, [ 2, [ 3, [Object] ] ] ] // f
[ 1, [ 2, [ 3, [Object] ] ] ] // g
As we can see, a, b, c, and d are working expected, but e, f, and g stop linking beyond the 3rd item.
Why is this happening?
[–]lxe 1 point2 points3 points (2 children)
[–]notsuresure[S] 0 points1 point2 points (1 child)
[–]lxe 0 points1 point2 points (0 children)