fixed isList so it checks for cycles

This commit is contained in:
Danny Yoo 2011-09-07 19:32:42 -04:00
parent 421310929f
commit 5bb2373305
5 changed files with 30 additions and 8 deletions

View File

@ -172,7 +172,7 @@
// Coerse a list back into a JavaScript array.
var listToArray = function(lst) {
var listToArray = function (lst) {
var result = [];
while (lst !== EMPTY) {
result.push(lst.first);
@ -185,12 +185,15 @@
// isList: Any -> Boolean
// Returns true if x is a list (a chain of pairs terminated by EMPTY).
var isList = function (x) {
while (x !== EMPTY) {
if (x instanceof Cons) {
x = x.rest;
} else {
return false;
}
var tortoise, hare;
tortoise = hare = x;
while (true) {
if (tortoise instanceof Cons) { tortoise = tortoise.rest; }
if (hare instanceof Cons) { hare = hare.rest; }
if (hare instanceof Cons) { hare = hare.rest; }
if (hare === EMPTY) { return true; }
if (tortoise === hare) { return false; }
if ((hare instanceof Cons) === false) { return false; }
}
return true;
};

View File

@ -2,6 +2,10 @@
("hello" "world")
true
true
true
false
true
true
false
true
hello

View File

@ -3,6 +3,11 @@
'(1 2 3)
(list "hello" "world")
(list? empty)
(list? '(1))
(list? '(1 2))
(list? 1)
(empty? empty)
(empty? '())
(cons? '())

View File

@ -22,3 +22,5 @@ jill
jane
true
false

View File

@ -70,4 +70,12 @@
(for-each displayln (map person-name (person-friends b)))
(newline)
(for-each displayln (map person-name (person-friends c)))
(newline))
(newline))
;; Make sure cyclic lists are treated correctly by list?
(shared ([a (cons 1 a)])
(begin
(displayln (pair? a))
(displayln (list? a))))