23 hours ago
my attempt to do the exercises in sicp.
Monday, December 13, 2010
sicp exercise 3.50
;; Exercise 3.50. Complete the following definition, which generalizes stream-map to allow procedures that take multiple arguments, analogous to map in section 2.2.3, footnote 12.
;; (define (stream-map proc . argstreams)
;; (if (<??> (car argstreams))
;; the-empty-stream
;; (<??>
;; (apply proc (map <??> argstreams))
;; (apply stream-map
;; (cons proc (map <??> argstreams))))))
(define (stream-enumerate-interval low high)
(if (> low high)
the-empty-stream
(cons-stream low
(stream-enumerate-interval (+ 1 low) high))))
(define (stream-filter pred stream)
(cond ((stream-null? stream) the-empty-stream)
((pred (stream-car stream))
(cons-stream (stream-car stream) (stream-filter pred (stream-cdr stream))))
(else
(stream-filter pred (stream-cdr stream)))))
(define (stream-ref s n)
(if (= n 0) (stream-car s)
(stream-ref (stream-cdr s) (- n 1))))
(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-map proc . argstreams )
(if (stream-null? (car argstreams))
the-empty-stream
(cons-stream
(apply proc (map stream-car argstreams))
(apply stream-map
(cons proc (map stream-cdr argstreams))))))
(define (add-streams s1 s2) (stream-map + s1 s2))
(define ones (cons-stream 1 ones))
(display (stream-ref ones 100))(newline)
(define fibs (cons-stream 0 (cons-stream 1 (add-streams (stream-cdr fibs) fibs))))
(display (stream-ref fibs 100))(newline)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment