stream.scm 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. ;;; -*- Mode: Scheme; scheme48-package: lazy-streams -*-
  2. ;;;; Lazy Streams
  3. ;;; This code is written by Taylor R. Campbell and Andreas Rottmann
  4. ;;; and placed in the Public Domain. All warranties are disclaimed.
  5. ;;;
  6. (define-syntax stream-cons
  7. (syntax-rules ()
  8. ((STREAM-CONS a d)
  9. (DELAY (CONS a d)))))
  10. (define stream-nil (delay '()))
  11. (define-syntax define-stream-unop
  12. (syntax-rules ()
  13. ((DEFINE-STREAM-UNOP stream-op op)
  14. (DEFINE (stream-op STREAM) (op (FORCE STREAM))))))
  15. (define-stream-unop stream-null? null?)
  16. (define-stream-unop stream-pair? pair?)
  17. (define-stream-unop stream-car car)
  18. (define-stream-unop stream-cdr cdr)
  19. (define (stream->list stream)
  20. (let ((datum (force stream)))
  21. (if (pair? datum)
  22. (cons (car datum)
  23. (stream->list (cdr datum)))
  24. datum)))
  25. (define (list->stream list)
  26. (lazy (if (pair? list)
  27. (stream-cons (car list)
  28. (list->stream (cdr list)))
  29. (eager list))))
  30. (define (string->stream string)
  31. (let recur ((index 0))
  32. (lazy (if (= index (string-length string))
  33. stream-nil
  34. (stream-cons (string-ref string index)
  35. (recur (+ index 1)))))))
  36. (define (vector->stream vector)
  37. (let recur ((index 0))
  38. (lazy (if (= index (vector-length vector))
  39. stream-nil
  40. (stream-cons (vector-ref vector index)
  41. (recur (+ index 1)))))))
  42. ;** Be careful! This operation is potentially dangerous.
  43. (define (stream-difference earlier later)
  44. (lazy (if (eq? earlier later)
  45. stream-nil
  46. (stream-cons (stream-car earlier)
  47. (stream-difference (stream-cdr earlier)
  48. later)))))
  49. (define (stream-append . streams)
  50. (let outer-recur ((streams streams))
  51. (if (pair? streams)
  52. (let ((stream (car streams))
  53. (streams (cdr streams)))
  54. (let inner-recur ((stream stream))
  55. (lazy (if (stream-pair? stream)
  56. (stream-cons (stream-car stream)
  57. (lazy (inner-recur (stream-cdr stream))))
  58. (outer-recur streams)))))
  59. stream-nil)))
  60. ;; loop iterator
  61. (define-syntax in-stream
  62. (syntax-rules ()
  63. ((_ (elt-var stream-var) (stream-expr) cont . env)
  64. (cont
  65. () ;Outer bindings
  66. ((stream-var stream-expr ;Loop variables
  67. (stream-cdr stream-var)))
  68. () ;Entry bindings
  69. ((stream-null? stream-var)) ;Termination conditions
  70. (((elt-var) (stream-car stream-var))) ;Body bindings
  71. () ;Final bindings
  72. . env))
  73. ;; Optional stream variable is optional
  74. ((_ (elt-var) (stream-expr) cont . env)
  75. (in-stream (elt-var stream) (stream-expr) cont . env))))