record.scm 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. ; Part of Scheme 48 1.9. See file COPYING for notices and license.
  2. ; Authors: Richard Kelsey
  3. (define-data-type list
  4. (pair? (cons car cdr)
  5. (car integer car set-car!)
  6. (cdr list cdr set-cdr!))
  7. (null? null))
  8. ; Also want pair->list (but probably not null->list).
  9. ; That means that PAIR is a separate type, which is not what ML does.
  10. ; Does the constructor make a pair or a list? Two constructors?
  11. ; The minimal version needs the pair-maker and pair->list.
  12. (define-data-type list
  13. (pair pair->list
  14. (make-pair car cdr)
  15. (car integer car set-car!)
  16. (cdr list cdr set-cdr!))
  17. (null))
  18. (define (cons x y)
  19. (pair->list (make-pair x y)))
  20. ; Could write it this way from scratch.
  21. (define-record-type :pair
  22. (make-pair car cdr)
  23. (car integer car set-car!)
  24. (cdr list cdr set-cdr!))
  25. (define-data-type :list
  26. (pair :pair)
  27. (null? null))
  28. ; pair->list needs to cons, especially if there are multiple options.
  29. ; This does show that the basic idea is sound - only the implementation
  30. ; changes from ML. Polymorphic lists would be tough this way.
  31. (define (member? list x)
  32. (let loop ((list list))
  33. (cond ((null? list)
  34. #f)
  35. ((= x (car list))
  36. #t)
  37. (else
  38. (loop (cdr list))))))
  39. (define (member? list x)
  40. (let loop ((list list))
  41. (delistify list
  42. ((null)
  43. #f)
  44. ((pair head tail)
  45. (if (= x head)
  46. #t
  47. (loop tail))))))
  48. (define (reverse! list)
  49. (if (or (null? list)
  50. (null? (cdr list)))
  51. list
  52. (let loop ((list list) (prev null))
  53. (let ((next (cdr list)))
  54. (set-cdr! list prev)
  55. (if (null? next)
  56. list
  57. (loop next list))))))
  58. ; Not terrible.
  59. (define (reverse! list)
  60. (delistify list
  61. ((null)
  62. list)
  63. ((pair . first-pair)
  64. (delistify (cdr first-pair)
  65. ((null)
  66. list)
  67. ((pair)
  68. (let loop ((pair first-pair) (prev null))
  69. (let ((next (cdr pair)))
  70. (set-cdr! pair prev)
  71. (delistify next
  72. ((null)
  73. pair)
  74. ((pair . next-pair)
  75. (loop next-pair next))))))))))