The base case is in the question is wrong, it's easier (and less error-prone) to simply state that a list is ordered if it has less than two elements. That's what was causing problems in your code, because the base case is ill-defined, your procedure enters in the second case when it shouldn't. When the list has less than two elements, you can't use cadr
. To fix your implementation do this:
(define (ordered e)
(if (< (length e) 2)
#t
(if (> (car e) (cadr e))
#f
(ordered (cdr e)))))
You can express the solution to this problem more concisely by using cond
, and you can avoid using length
(which depending on the implementation could be an O(n)
operation) like this:
(define (ordered e)
(cond ((or (null? e) (null? (cdr e))) #t)
((> (car e) (cadr e)) #f)
(else (ordered (cdr e)))))