Skip to main content
Code Review

Return to Revisions

2 of 2
deleted 1 character in body
Renzo
  • 2.1k
  • 15
  • 17

First, a note about testing: inside singleton-list? you check if the argument is a pair, while it is called by all-same? always with a non-empty list, so the test will be always true.

So you can simplify the program by eliminating the auxiliary function and replacing, inside the definition of all-same?, the second branch of the conditional with the only significant test:

((null? (cdr ls)) #t)

Then, note that your function returns a boolean value, and each branch of the cond and the inner if returns a boolean value. This is a good reason to perform a little simplification of the function, by using and and or as control structures (this is typical of the lisp languages). So the function could be redefined as:

(define all-same?
 (lambda (ls)
 (and (not (null? ls))
 (or (null? (cdr ls))
 (and (equal? (car ls) (cadr ls))
 (all-same? (cdr ls)))))))

Finally, it may be questionable to decide that the function should return false when the list is empty, since in mathematics the universal quantifier is true even for an empty set. So, in case the function could be defined to return true even if the list is empty ("there are no elements, so there are no two element different"), we could further simplify the function in the following way:

(define all-same?
 (lambda (ls)
 (or (null? ls)
 (null? (cdr ls))
 (and (equal? (car ls) (cadr ls))
 (all-same? (cdr ls))))))
Renzo
  • 2.1k
  • 15
  • 17
default

AltStyle によって変換されたページ (->オリジナル) /