Reputation: 15
I am trying to make a function that returns true or false if a list is in order. I can't figure out how to make it recursive. I keep getting error messages on the last line: define: expected only one expression for the function body, but found 1 extra part
(check-expect (is-sorted? (list)) true)
(check-expect (is-sorted? (list "A")) true)
(check-expect (is-sorted? (list "B" "A")) false)
(check-expect (is-sorted? (list "A" "B")) true)
(check-expect (is-sorted? (list "A" "C" "B")) false)
(check-expect (is-sorted? (list "A" "B" "C")) true)
(define (is-sorted? lst)
(cond
((empty-list? lst) true)
((= (length lst) 1) true) ;return true if there is only one element.
((string<? (first lst) second lst) true) ;If the first element is smaller than the second
;return true.
(else (is-sorted? (rest lst))))) ;do the above steps on the rest of the elements in the list.
Upvotes: 0
Views: 57
Reputation: 236004
Notice that you're not considering the case when the procedure should return false
, and that you exit prematurely when you find that an element is sorted with respect to the next element (you need to keep iterating! it's just one match, what about the others?). The solution is simple, just negate the condition for this case and ask if it's not sorted return false
. Like this:
(define empty-list? empty?)
(define (is-sorted? lst)
(cond
((empty-list? lst) true)
((empty-list? (rest lst)) true)
((string>=? (first lst) (second lst)) false)
(else (is-sorted? (rest lst)))))
It works with your test cases:
(is-sorted? (list)) ; true
(is-sorted? (list "A")) ; true
(is-sorted? (list "B" "A")) ; false
(is-sorted? (list "A" "B")) ; true
(is-sorted? (list "A" "C" "B")) ; false
(is-sorted? (list "A" "B" "C")) ; true
Upvotes: 0