创建函数AllEqual?(L),它将给出(至少2个)元素的列表,如果所有元素都相同则返回#t,否则#f
(define (allequal? l)
(if (< (length l) 2)
#t
(equal? (car l) (allequal? (cdr l)))))
答案 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)))))