srfi-95.scm 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. ; Part of Scheme 48 1.9. See file COPYING for notices and license.
  2. ; Authors: David van Horn, Mike Sperber, Marcus Crestani
  3. ;;; "sort.scm" defines: sorted?, merge, merge!, sort, sort!
  4. (define (sorted? seq less? . opt-key)
  5. (define key (if (null? opt-key) (lambda (x) x) (car opt-key)))
  6. (define less-key? (lambda (a b) (less? (key a) (key b))))
  7. (cond
  8. ((array? seq)
  9. (olin:vector-sorted? less-key? (array->vector seq)))
  10. ((vector? seq)
  11. (olin:vector-sorted? less-key? seq))
  12. (else
  13. (olin:list-sorted? less-key? seq))))
  14. (define (merge a b less? . opt-key)
  15. (define key (if (null? opt-key) (lambda (x) x) (car opt-key)))
  16. (define less-key? (lambda (a b) (less? (key a) (key b))))
  17. (cond
  18. ((and (vector? a) (vector? b))
  19. (olin:vector-merge less-key? a b))
  20. (else
  21. (olin:list-merge less-key? a b))))
  22. (define (merge! a b less? . opt-key)
  23. (define key (if (null? opt-key) (lambda (x) x) (car opt-key)))
  24. (define less-key? (lambda (a b) (less? (key a) (key b))))
  25. (cond
  26. ((and (vector? a) (vector? b))
  27. (let ((v (make-vector (+ (vector-length a) (vector-length b)))))
  28. (olin:vector-merge! less-key? v a b)
  29. v))
  30. (else
  31. (olin:list-merge! less-key? a b))))
  32. (define (sort seq less? . opt-key)
  33. (define key (if (null? opt-key) (lambda (x) x) (car opt-key)))
  34. (define less-key? (lambda (a b) (less? (key a) (key b))))
  35. (cond
  36. ((vector? seq)
  37. (olin:vector-sort less-key? seq))
  38. ((array? seq)
  39. (apply vector->array
  40. (olin:vector-sort less-key? (array->vector seq))
  41. '#()
  42. (array-dimensions seq)))
  43. (else
  44. (olin:list-sort less-key? seq))))
  45. (define (sort! seq less? . opt-key)
  46. (define key (if (null? opt-key) (lambda (x) x) (car opt-key)))
  47. (define less-key? (lambda (a b) (less? (key a) (key b))))
  48. (cond
  49. ((vector? seq)
  50. (olin:vector-sort! less-key? seq)
  51. seq)
  52. ((array? seq)
  53. (let ((v (olin:vector-sort less-key? (array->vector seq))))
  54. (apply vector->array v '#() (array-dimensions seq))))
  55. (else
  56. (olin:list-sort! less-key? seq))))