;;; see SICP 3.5 (uses odd streams), srfi-40 (define-module stream-base/odd-with-promise ;; odd stream using gauche promises (export-all) (define-syntax stream-cons (syntax-rules () ((_ car cdr) (cons car (delay cdr))))) (define the-empty-stream '()) (define stream-null? null?) (define stream-car car) (define (stream-cdr s) (when (is-a? (cdr s) ) (set-cdr! s (force (cdr s)))) (cdr s))) ;; ----------------------------------------------------------------- (define-module stream-base/odd-r5rs ;; odd stream using R5RS primitives (export-all) (define-syntax stream-cons (syntax-rules () ((_ car cdr) (cons car (lambda () cdr))))) (define the-empty-stream '()) (define stream-null? null?) (define stream-car car) (define (stream-cdr s) (when (procedure? (cdr s)) (set-cdr! s ((cdr s)))) (cdr s))) ;; ----------------------------------------------------------------- (define-module stream/odd ;; pick a base implementation (import stream-base/odd-with-promise) (export-all) (define (stream-ref s n) (if (zero? n) (stream-car s) (stream-ref (stream-cdr s) (- n 1)))) (define (stream-map proc s) (if (stream-null? s) the-empty-stream (stream-cons (proc (stream-car s)) (stream-map proc (stream-cdr s))))) (define (stream-for-each proc s) (if (stream-null? s) 'done (begin (proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) (define (stream-filter pred stream) (cond ((stream-null? stream) the-empty-stream) ((pred (stream-car stream)) (stream-cons (stream-car stream) (stream-filter pred (stream-cdr stream)))) (else (stream-filter pred (stream-cdr stream))))) (define (stream-from-to low high) (if (> low high) the-empty-stream (stream-cons low (stream-from-to (+ low 1) high)))))