我在这段代码中做错了什么?我试图检查列表中的所有元素是否相同,无论测试用例我得到#f

时间:2014-10-26 17:29:59

标签: recursion scheme

创建函数AllEqual?(L),它将给出(至少2个)元素的列表,如果所有元素都相同则返回#t,否则#f

(define (allequal? l)
  (if (< (length l) 2) 
      #t
      (equal? (car l) (allequal? (cdr l)))))

1 个答案:

答案 0 :(得分:1)

(equal? (car l) (allequal? (cdr l)))

测试(car l)equal?(allequal? ...)。由于allequal?返回布尔值(#t#f),因此您测试(car l)#t还是#f,这不是您想要的

您需要比较前两个元素(如果有),然后递归到列表的cdr

(define (allequal? l)
  (if (< (length l) 2)
      #t 
      (and (equal? (car l) (cadr l))
           (allequal? (cdr l)))))

或者,更简单,

(define (allequal? l)
  (or (< (length l) 2)
      (and (equal? (car l) (cadr l))
           (allequal? (cdr l)))))

甚至

(define (allequal? l)
  (or (null? l)
      (null? (cdr l))
      (and (equal? (car l) (cadr l))
           (allequal? (cdr l)))))