sets.scm 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #lang racket
  2. (provide sorted-list-insert intersects? intersection union subset-of?)
  3. ;; A set is represented by a sorted list of increasing integers
  4. ;; it may be more efficient to replace these with trees in future
  5. (define (sorted-list-insert key x l)
  6. (if (null? l)
  7. (list x)
  8. (let ((x-k (key x))
  9. (y (key (car l))))
  10. (cond ((<= x-k y) (cons x l))
  11. ((> x-k y) (cons (car l) (sorted-list-insert key x (cdr l))))))))
  12. (define (intersects? key s1 s2)
  13. (cond ((null? s1) #f)
  14. ((null? s2) #f)
  15. (else
  16. (let ((x (key (car s1)))
  17. (y (key (car s2))))
  18. (cond ((< x y) (intersects? key (cdr s1) s2))
  19. ((= x y) #t)
  20. ((> x y) (intersects? key s1 (cdr s2))))))))
  21. (define (intersection key s1 s2)
  22. (cond ((null? s1) '())
  23. ((null? s2) '())
  24. (else
  25. (let ((x (key (car s1)))
  26. (y (key (car s2))))
  27. (cond ((< x y) (intersection key (cdr s1) s2))
  28. ((= x y) (cons (car s1) (intersection key (cdr s1) (cdr s2))))
  29. ((> x y) (intersection key s1 (cdr s2))))))))
  30. (define (union key s1 s2)
  31. (cond ((null? s1) s2)
  32. ((null? s2) s1)
  33. (else
  34. (let ((x (key (car s1)))
  35. (y (key (car s2))))
  36. (cond ((< x y) (cons (car s1) (union key (cdr s1) s2)))
  37. ((= x y) (cons (car s1) (union key (cdr s1) (cdr s2))))
  38. ((> x y) (cons (car s2) (union key s1 (cdr s2)))))))))
  39. (define (subset-of? key s1 s2)
  40. ;; s1 is a subset of s2?
  41. (cond ((null? s1) #t)
  42. ((null? s2) #f)
  43. (else
  44. (let ((x (key (car s1)))
  45. (y (key (car s2))))
  46. (cond ((< x y) #f)
  47. ((= x y)
  48. ;; NB. dont cdr s2 here in case of multiple occurences
  49. (subset-of? key (cdr s1) s2))
  50. ((> x y) (subset-of? key s1 (cdr s2))))))))