이 문제 역시 코드를 보고 결과를 예측하는 문제입니다.

위와 같이 나옵니다.^^
seq는 1부터 해당 숫자까지 합을 나타냅니다.
그리고 y는 그 스트림 중 짝수를, z는 5의 배수만을 골라냅니다.
따라서 (stream-ref y 7)은 7번째 짝수이므로 136이 나옵니다.
(정확하게는 0부터 시작하므로 8번째 짝수입니다.)
다음으로 5의 배수인 z를 출력하면 위와 같습니다.
문제에서 memo-proc를 쓴 경우와 쓰지 않은 경우를 비교하라고 하였습니다.
하지만 memo-proc를 쓰지 않은 경우의 코드를 만드니
Scheme이 기본으로 제공하는 delay를 사용하여 그 차이를 확인할 수 없었습니다.
과연 무엇이 다른지 예측할 수 없었기에 아쉬운 점입니다.
참조
해럴드 애빌슨, 김재우 역, <컴퓨터 프로그램의 구조와 해석>, 인사이트, 2007, pp. 423
; stream
(define true (= 0 0))
(define false (= 1 0))
(define (delay x)
(memo-proc (lambda () x)))
(define (force delayed-object)
(delayed-object))
(define (cons-stream a b)
(cons a (delay b)))
(define the-empty-stream '())
(define stream-null? null?)
(define (stream-car stream) (car stream))
(define (stream-cdr stream) (force (cdr stream)))
; section 3.5
(define (stream-ref s n)
(if (= n 0)
(stream-car s)
(stream-ref (stream-cdr s) (- n 1))))
;(define (stream-map proc s)
; (if (stream-null? s)
; the-empty-stream
; (cons-stream (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 (display-stream s)
(stream-for-each display-line s))
(define (display-line x)
(newline)
(display x))
(define (stream-enumerate-interval low high)
(if (> low high)
the-empty-stream
(cons-stream
low
(stream-enumerate-interval (+ low 1) 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 (memo-proc proc)
(let ((already-run? false) (result false))
(lambda ()
(if (not already-run?)
(begin (set! result (proc))
(set! already-run? true)
result)
result))))
; exercise 3.50
(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))))))
; exercise 3.52
(define sum 0)
(define (accum x)
(set! sum (+ x sum))
sum)
; execute
(define seq (stream-map accum (stream-enumerate-interval 1 20)))
(define y (stream-filter even? seq))
(define z (stream-filter (lambda (x) (= (remainder x 5) 0))
seq))
(stream-ref y 7)
(display-stream z)
- SICP Exercise 연습문제 3.55 (0)2008/07/19
- SICP Exercise 연습문제 3.54 (0)2008/07/19
- SICP Exercise 연습문제 3.53 (0)2008/07/19
- SICP Exercise 연습문제 3.52 (0)2008/07/19
- SICP Exercise 연습문제 3.51 (0)2008/07/19
- SICP Exercise 연습문제 3.50 (0)2008/07/19
- SICP Exercise 연습문제 3.48 (0)2008/07/18
글에 잘못된 점, 다른 점, 부족한 점이 있다면 지적해주세요.
댓글, 트랙백, 메일 모두 고맙습니다.







댓글을 달아 주세요