The program consists of two functions: the helper predicate function singleton-list?
that checks whether a given list contains only one item and the function that does the actual job all-same?
.
;; Predicate function: singleton-list?
;; -----------------------------------
;; The singleton-list? predicate function tests whether a list contains only a
;; single item. That is, if the list provided has got only one element in it,
;; the function returns true. In all other cases, the function returns a value
;; of false. First it checks if the object we're sent is in fact a list. If it
;; is, we check whether "cdr" returns a nonempty list. If it does, that means
;; there is more than one item in the list and thus a value of false is
;; returned.
;;
;; Usage examples:
;; (singleton-list? '(A)) => #t
;; (singleton-list? '(A B C)) => #f
;; (singleton-list? '()) => #f
(define singleton-list?
(lambda (ls)
(and (pair? ls) (null? (cdr ls)))))
;; Predicate function: all-same?
;; -----------------------------
;; The all-same? predicate function tests whether all elements in a given list
;; are identical. Fist it checks if the list passed in is an empty list. If it
;; is, we return a value of false because the concept of sameness does not make
;; a whole lot of sense when there are no things to be compared against each
;; other. When there is only one item in a list, we return true. Otherwise,
;; we've got a list with more than one item in it. We compare the first item
;; with the second. If they're equal, we call the function recursively with our
;; list where the first element has been removed.
;;
;; Usage examples:
;; (all-same? '(A A A)) => #t
;; (all-same? '(A B A)) => #f
;; (all-same? '(A)) => #t
;; (all-same? '()) => #f
(define all-same?
(lambda (ls)
(cond ((null? ls) #f) ; If empty list, return false
((singleton-list? ls) #t) ; If single-item list, return true
(else (if (equal? (car ls) (car (cdr ls)))
(all-same? (cdr ls))
#f)))))