; Copyright (C) 2006 Will M. Farr ; ; This program is free software; you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation; either version 2 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License along ; with this program; if not, write to the Free Software Foundation, Inc., ; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. (module streams mzscheme (require (only (lib "1.ss" "srfi") any)) (provide stream? stream-car stream-cdr stream-ref stream-cons (rename my-stream stream) stream-map stream-filter stream-take stream-converged? stream-take-converged) (define-struct stream (a b) #f) (define stream-car stream-a) (define (stream-cdr s) (force (stream-b s))) (define (stream-ref s n) (if (= n 0) (stream-car s) (stream-ref (stream-cdr s) (- n 1)))) (define-syntax stream-cons (syntax-rules () ((cons-stream car cdr) (make-stream car (delay cdr))))) (define-syntax my-stream (syntax-rules () ((stream a) (stream-cons a ())) ((stream a b) (stream-cons a b)) ((stream a b ...) (stream-cons a (my-stream b ...))))) (define (stream-map f . ss) (stream-cons (apply f (map stream-car ss)) (apply stream-map f (map stream-cdr ss)))) (define (stream-for-each f . ss) (apply f (map stream-car ss)) (stream-for-each f (map stream-cdr ss))) (define (stream-filter test? s) (let ((s1 (stream-car s))) (if (test? s1) (stream-cons s1 (stream-filter test? (stream-cdr s))) (stream-filter test? (stream-cdr s))))) (define (stream-take n s) (if (= n 0) '() (cons (stream-car s) (stream-take (- n 1) (stream-cdr s))))) (define (stream-converged? s) (= (stream-car s) (stream-ref s 1))) (define (stream-take-converged s) (if (stream-converged? s) (stream-car s) (stream-take-converged (stream-cdr s)))))