1 day ago
my attempt to do the exercises in sicp.
Wednesday, December 22, 2010
sicp exercise 3.67
;; Exercise 3.67. Modify the pairs procedure so that (pairs integers integers) will produce the stream of all pairs of integers (i,j) (without the condition i < j). Hint: You will need to mix in an additional stream.
(define (display-line str)
(display str)
(newline))
(define (display-stream str num)
(define (internal index)
(if (> index num) 'printed
(begin
(display-line (stream-ref str index))
(internal (+ 1 index)))))
(internal 0))
(define (interleave s1 s2)
(if (stream-null? s1)
s2
(cons-stream (stream-car s1)
(interleave s2 (stream-cdr s1)))))
(define (pairs s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(interleave
(stream-map (lambda(x)(list x (stream-car t)))
(stream-cdr s))
(pairs (stream-cdr s) (stream-cdr t))))))
(define (integers-from-n n)
(cons-stream n (integers-from-n (+ 1 n))))
(define integers (integers-from-n 1))
(define int-pairs (pairs integers integers))
(newline)
(display-stream int-pairs 20)
;; Answer:
;Loading "sicp_prob_03.67.scm"...
;(1 1)
;(1 2)
;(2 1)
;(1 3)
;(2 2)
;(1 4)
;(3 1)
;(1 5)
;(2 3)
;(1 6)
;(4 1)
;(1 7)
;(3 2)
;(1 8)
;(5 1)
;(1 9)
;(2 4)
;(1 10)
;(6 1)
;(1 11)
;(3 3)
;... done
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment