Sorting in Kawa

Chris Bitmead chris@bitmead.com
Fri Dec 20 10:36:00 GMT 2002


I've made the following functions that are more or less compatible with 
SLIB. I'm wondering though if I should have just ported SLIB's 
comparison. Is it better to wrap up built-in Java functions or is it 
better to port existing Scheme libraries like SLIB?

Also, wouldn't it be a good idea if Scheme List and vector implement 
Clonable like most Java collections? That way I could copy them using 
Java mechanisms which might be convenient if trying to sort other types 
of java collection.


(define-simple-class <comparator> (<java.util.Comparator>)
  (compare init-keyword: compare:)
  ((compare (o1 :: <java.lang.Object>) (o2 :: <java.lang.Object>)) :: <int>
   ((slot-ref (this) 'compare) o1 o2)))

(define (sort-compare! sequence compare)
  (let ((comparator (make <comparator> compare: compare)))
    (invoke-static <java.util.Collections> 'sort sequence comparator)
    sequence))

(define (copy-list sequence)
  (apply list sequence))

(define (copy-vector vec)
  (apply vector vec))

(define (sort-compare sequence compare)
  (if (list? sequence)
      (sort-compare! (copy-list sequence) compare)
      (sort-compare! (copy-vector sequence) compare)))

(define (sort! sequence less?)
  (define (compare o1 o2)
    (if (less? o1 o2) -1 1))
  (sort-compare sequence compare))

(define (sort sequence less?)
  (if (list? sequence)
      (sort! (copy-list sequence) less?)
      (sort! (copy-vector sequence) less?)))






More information about the Kawa mailing list