I'll start with your code so far, and find the problems with it:
(define (same-numbers? lst)
(cond
[(empty? (rest lst)) (first lst)]
[else (equal? (first lst)(same-numbers? (rest lst)))]))
The first problem I see is with the base case: if lst
is a list of numbers then (first lst)
will be a number, not a boolean like you wanted.
;; same-numbers? : [Listof Number] -> Boolean
To fix this, the base case should return #true
:
(define (same-numbers? lst)
(cond
[(empty? (rest lst)) #true]
[else (equal? (first lst) (same-numbers? (rest lst)))]))
The next problem I see is with the recursive case: since same-numbers?
returns a boolean, you shouldn't use equal?
as if you're expecting a number. Instead use equal?
between the first
and the second
:
(define (same-numbers? lst)
(cond
[(empty? (rest lst)) #true]
[else ... (equal? (first lst) (second lst)) ... (same-numbers? (rest lst)) ...]))
Now the ...
s around that need to be filled with stuff that combines the information in "first two equal" and "rest same-numbers". They're all equal when the first two are equal AND the rest are the same, so fill in the ...
s with and
to combine them:
(define (same-numbers? lst)
(cond
[(empty? (rest lst)) #true]
[else (and (equal? (first lst) (second lst)) (same-numbers? (rest lst)))]))
If I type in:
> (same-numbers? (cons 5 (cons 5 (cons 5 empty))))
#true
There's still one problem left: the empty list. So just add another cond
case for it:
;; same-numbers? : [Listof Number] -> Boolean
(define (same-numbers? lst)
(cond
[(empty? lst) #true]
[(empty? (rest lst)) #true]
[else (and (equal? (first lst) (second lst)) (same-numbers? (rest lst)))]))
Using it:
> (same-numbers? empty)
#true
> (same-numbers? (cons 5 empty))
#true
> (same-numbers? (cons 5 (cons 5 (cons 5 empty))))
#true
> (same-numbers? (cons 5 (cons 5 (cons 6 empty))))
#false
(apply = lst)
– Atharva Shukla(same-numbers? (list 5 5 5))
returns#f
.(same-numbers? (list 5 5))
returns#t
.(same-numbers? (list 5))
returns5
.(same-numbers? (list))
errors out. first thing to do about a recursive function definition is to take care that it always returns same type of result in all cases. – Will Ness