#stream.scm# 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. (define-module (myutil stream)
  2. #:export (make-stream
  3. stream-car
  4. stream-cdr
  5. stream-next
  6. stream-get-nth
  7. position-in-stream
  8. natural-numbers
  9. rational-numbers))
  10. (define (make-stream proc start)
  11. (cons start
  12. (λ ()
  13. (make-stream proc (proc start)))))
  14. (define stream-car car)
  15. (define (stream-cdr stream)
  16. ((cdr stream)))
  17. (define stream-next stream-cdr) ; convenience procedure
  18. (define (stream-get-nth stream n)
  19. (cond [(= n 0)
  20. (stream-car stream)]
  21. [else
  22. (stream-get-nth (stream-cdr stream)
  23. (- n 1))]))
  24. (define natural-numbers
  25. (make-stream (λ (x) (+ x 1))
  26. 0))
  27. (define (numerator fraction)
  28. (car fraction))
  29. (define (denominator fraction)
  30. (cdr fraction))
  31. (define (make-fraction num denom)
  32. (cons num denom))
  33. (define (next-rational-fraction fraction)
  34. (let ([num (numerator fraction)]
  35. [denom (denominator fraction)])
  36. (cond [(= num 1)
  37. (if (odd? denom)
  38. (make-fraction num
  39. (1+ denom))
  40. (make-fraction (1+ num)
  41. (1- denom)))]
  42. [(= denom 1)
  43. (if (odd? num)
  44. (make-fraction (1- num)
  45. (1+ denom))
  46. (make-fraction (1+ num)
  47. denom))]
  48. [else (if (odd? (+ num denom))
  49. (make-fraction (1+ num)
  50. (1- denom))
  51. (make-fraction (1- num)
  52. (1+ denom)))])))
  53. (define rational-numbers
  54. (make-stream next-rational-fraction
  55. (make-fraction 1 1)))
  56. (define (position-in-stream elem a-stream)
  57. (define (iter stream n)
  58. (cond [(equal? (stream-car stream) elem) n]
  59. [else (iter (stream-next stream) (1+ n))]))
  60. (iter a-stream 0))
  61. rational-numbers
  62. natural-numbers