X10D
X10D

Reputation: 620

Sort function with customizable comparision function

After writing:

(define (sort-asc l)
  (cond ((eq? l '()) '())
        ((eq? (cdr l) '()) (list (car l)))
        ((< (car l) (cadr l)) (cons (car l) (sort-asc (cdr l)) ))
        (else (cons (cadr l) (sort-asc (cons (car l) (cddr l)) )))))

How do you write a function that can additionally take a comparison function as a parameter?

Tried:

(define (sort-f l f)
  (cond ((eq? l '()) '())
        ((eq? (cdr l) '()) (list (car l)))
        ((lambda ()(f (car l) (cadr l))) (cons (car l) (sort-f (cdr l) f)))
        (else (cons (cadr l) (sort-f (cons (car l) (cddr l)) f)))))

But (sort-f '(4 3 8 2 5) <) returns the same list. p.s. Is there any way to make this code look more elegant by somehow rewriting of all the car's, cadr's and cdr's?

Upvotes: 1

Views: 67

Answers (1)

C. K. Young
C. K. Young

Reputation: 223003

Your third cond branch condition should be (f (car l) (cadr l)), not (lambda () ...). The lambda expression returns a procedure (which is not invoked), and since all procedures are truthy, the fourth (else) branch is never reached.

That is,

((lambda ()(f (car l) (cadr l))) (cons (car l) (sort-f (cdr l) f)))

should be

((f (car l) (cadr l)) (cons (car l) (sort-f (cdr l) f)))

Upvotes: 1

Related Questions