my attempt to do the exercises in sicp.

Sunday, December 19, 2010

sicp exercise 3.58


;; Exercise 3.58.  Give an interpretation of the stream computed by the following procedure:
;;
;;(define (expand num den radix)
;;  (cons-stream
;;   (quotient (* num radix) den)
;;   (expand (remainder (* num radix) den) den radix)))
;;
;;(Quotient is a primitive that returns the integer quotient of two integers.) What are the successive elements produced by (expand 1 7 10) ? What is produced by (expand 3 8 10) ?


(define (expand num den radix)
  (cons-stream
   (quotient (* num radix) den)
   (expand (remainder (* num radix) den) den radix)))

(newline)
(display (stream-ref (expand 1 7 10) 0)) (newline)
(display (stream-ref (expand 1 7 10) 1)) (newline)
(display (stream-ref (expand 1 7 10) 2)) (newline)
(display (stream-ref (expand 1 7 10) 3)) (newline)
(display (stream-ref (expand 1 7 10) 4)) (newline)
(display (stream-ref (expand 1 7 10) 5)) (newline)
(display (stream-ref (expand 1 7 10) 6)) (newline)
(display (stream-ref (expand 1 7 10) 7)) (newline)
(display (stream-ref (expand 1 7 10) 8)) (newline)

(newline)
(newline)
(newline)

(display (stream-ref (expand 3 8 10) 0)) (newline)
(display (stream-ref (expand 3 8 10) 1)) (newline)
(display (stream-ref (expand 3 8 10) 2)) (newline)
(display (stream-ref (expand 3 8 10) 3)) (newline)
(display (stream-ref (expand 3 8 10) 4)) (newline)
(display (stream-ref (expand 3 8 10) 5)) (newline)
(display (stream-ref (expand 3 8 10) 6)) (newline)
(display (stream-ref (expand 3 8 10) 7)) (newline)
(display (stream-ref (expand 3 8 10) 8)) (newline)

; Output:
;Loading "sicp_prob_03.58.scm"...
;1
;4
;2
;8
;5
;7
;1
;4
;2
;
;
;
;3
;7
;5
;0
;0
;0
;0
;0
;0
;... done


No comments: