sortp.scm 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. ;;; The sort package -- sorted predicates
  2. ;;; Olin Shivers 10/98.
  3. ;;;
  4. ;;; (list-sorted? < lis) -> boolean
  5. ;;; (vector-sorted? < v [start end]) -> boolean
  6. (define (list-sorted? < list)
  7. (or (not (pair? list))
  8. (let lp ((prev (car list)) (tail (cdr list)))
  9. (or (not (pair? tail))
  10. (let ((next (car tail)))
  11. (and (not (< next prev))
  12. (lp next (cdr tail))))))))
  13. (define (vector-sorted? elt< v . maybe-start+end)
  14. (call-with-values
  15. (lambda () (vector-start+end v maybe-start+end))
  16. (lambda (start end)
  17. (or (>= start end) ; Empty range
  18. (let lp ((i (+ start 1)) (vi-1 (vector-ref v start)))
  19. (or (>= i end)
  20. (let ((vi (vector-ref v i)))
  21. (and (not (elt< vi vi-1))
  22. (lp (+ i 1) vi)))))))))
  23. ;;; Copyright and porting non-notices
  24. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  25. ;;; Give me a break. It's fifteen lines of code. I place this code in the
  26. ;;; public domain; help yourself.
  27. ;;;
  28. ;;; If your Scheme has a faster mechanism for handling optional arguments
  29. ;;; (e.g., Chez), you should definitely port over to it. Note that argument
  30. ;;; defaulting and error-checking are interleaved -- you don't have to
  31. ;;; error-check defaulted START/END args to see if they are fixnums that are
  32. ;;; legal vector indices for the corresponding vector, etc.