Question

I'm just started learning scheme and can't quite understand why this function does not work:

;(define (sort l)
  (define (sorted? l)
    (if (= (length l) 2)            
        ; if simple list:
        (if (< (head l) (tail l)) 
            #t  
            #f) 
        ; if complex list:
        (if (and (< (head l) (head (tail l))) 
                 (sorted? (tail l)))
            #t  
            #f)))

Output:

(sorted? (1 0)) . . procedure application: expected procedure, given: 1; arguments were: 0 (sorted? '(1 0)) . . <: expects type as 2nd argument, given: (0); other arguments were: 1

Racket, R5RS

Was it helpful?

Solution

This is because you compare an integer and a list, cadr or if (< (head l) (head (tail l))) instead of if (< (head l) (tail l)) after a line ; if simple list would have more chances to work for you.

The following definition works for me:

(define (sorted? xs)
  (cond
    ((<= (length xs) 1)
     #t)
    ((< (car xs) (cadr xs))
     (sorted? (cdr xs)))
    (else #f)))

OTHER TIPS

What scheme do you use? In R5RS (scheme standard), use car and cdr to get head and tail.

And cdr will give you PAIR, not atom. That's working.

(define (sorted? l) (if (= (length l) 2)
; if simple list: (if (< (car l) (cadr l)) #t
#f) ; if complex list: (if (and (< (head l) (head (tail l))) (sorted? (tail l))) #t
#f)))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top