sorting - How to check if a list is sorted in Racket? -


i trying define function takes list argument , returns boolean (#t or #f) indicating if list sorted in ascending order. output of function should this:

(sorted? '(1 2 3 4 5))             ; => #t (sorted? '(1 2 5 6 4))             ; => #f (sorted? '("frank" "adam" "eve"))  ; => #f (sorted? '("adam" "eve" "frank"))  ; => #t 

here's attempt @ solution:

(define (sorted? lst)   (cond     [(< (length lst) 2]       [(<= (car lst) (cadr lst)) (sorted? (cdr lst))]     [(string? lst) (string<=? (car lst) (cadr lst)) (sorted? (cdr lst))]     [else #f])) 

i keep getting errors string part, , can't seem figure out i'm doing wrong. getting errors because have 2 different types in same definiton? i'm assuming since it's conditional statement if arguments in list don't fit condition, should ignored. i'm new @ , need help. please share knowledge if know i'm doing wrong , need fix this. thanks.

usually don't want mix numerical , lexical sort, lets imagine second can compare value:

(define (any<? b)   (cond ((and (number? a) (number? b)) (< b))         ((and (string? a) (string? b)) (string<? b))         ;; can add types here. default cast          ;; string , compare string         ;; nb! format racket specific          (else (string<? (format "~a" a) (format "~a" b)))))  

so lets sort something:

(define unsorted '(#\a  5 "hello" 9 (a c b) 10 (a b c) "50"))  ;; nb: sort racket specific, r6rs has list-sort  ;; arguments in reverse order. (define sorted (sort test any<?))  test2 ; ==> ((a b c) (a c b) 5 "50" 9 10 #\a "hello")  ;; using named let current element  ;; makes check null? once each pair (define (sorted? lst <)   (or (null? lst)       (let loop ((e (car lst)) (lst (cdr lst)))         (or (null? lst)             (and (not (< (car lst) e))                   (loop (car lst) (cdr lst)))))))  (sorted? unsorted any<?) ; ==> #f (sorted? sorted any<?)   ; ==> #t 

you wouldn't use any<? specific comparison procedure data if know type of elements in list. e.g.

(sorted? '("a" "b" "cd") string<?) ; ==> #t (sorted? '(4 7 3 5 9 3 4 6) <)     ; ==> #f 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -