sicp每日一題[2.49]

再思即可發表於2024-10-19

Exercise 2.49

Use segments->painter to define the following primitive painters:

a. The painter that draws the outline of the designated frame.
b. The painter that draws an “X” by connecting opposite corners of the frame.
c. The painter that draws a diamond shape by connecting the midpoints of the sides of the frame.
d. The wave painter.


這道題目我本來感覺不是很難,我按照題目要求把 frame 的3個點座標取出來,然後用 make-segment 連成線,但是做了半天總是不行,
上網搜了一下其他人的答案,發現他們都是直接傳的 segment-list,而不是傳 frame,而且之前定義的 make-vect, make-segment 也都用不了。。
必須先匯入 sicp-pict,然後再用它自帶的 vect 和 segment 來建立向量和線段。完整程式碼如下:

(#%require sicp-pict)


; a 
(define outline 
  (segments->painter 
   (list 
    (segment (vect 0.0 0.0) (vect 0.0 1.0)) 
    (segment (vect 0.0 0.0) (vect 1.0 0.0)) 
    (segment (vect 0.0 1.0) (vect 1.0 1.0)) 
    (segment (vect 1.0 0.0) (vect 1.0 1.0)))))

; b 
(define x-painter 
  (segments->painter 
   (list 
    (segment (vect 0.0 0.0) (vect 1.0 1.0)) 
    (segment (vect 0.0 1.0) (vect 1.0 0.0))))) 

; c
(define diamond 
  (segments->painter 
   (list 
    (segment (vect 0.0 0.5) (vect 0.5 1.0)) 
    (segment (vect 0.5 1.0) (vect 1.0 0.5)) 
    (segment (vect 1.0 0.5) (vect 0.5 0.0)) 
    (segment (vect 0.5 0.0) (vect 0.0 0.5))))) 

; d
(define wave 
  (segments->painter (list 
                      (segment (vect .25 0) (vect .35 .5)) 
                      (segment (vect .35 .5) (vect .3 .6)) 
                      (segment (vect .3 .6) (vect .15 .4)) 
                      (segment (vect .15 .4) (vect 0 .65)) 
                      (segment (vect 0 .65) (vect 0 .85)) 
                      (segment (vect 0 .85) (vect .15 .6)) 
                      (segment (vect .15 .6) (vect .3 .65)) 
                      (segment (vect .3 .65) (vect .4 .65)) 
                      (segment (vect .4 .65) (vect .35 .85)) 
                      (segment (vect .35 .85) (vect .4 1)) 
                      (segment (vect .4 1) (vect .6 1)) 
                      (segment (vect .6 1) (vect .65 .85)) 
                      (segment (vect .65 .85) (vect .6 .65)) 
                      (segment (vect .6 .65) (vect .75 .65)) 
                      (segment (vect .75 .65) (vect 1 .35)) 
                      (segment (vect 1 .35) (vect 1 .15)) 
                      (segment (vect 1 .15) (vect .6 .45)) 
                      (segment (vect .6 .45) (vect .75 0)) 
                      (segment (vect .75 0) (vect .6 0)) 
                      (segment (vect .6 0) (vect .5 .3)) 
                      (segment (vect .5 .3) (vect .4 0)) 
                      (segment (vect .4 0) (vect .25 0)) 
                      )))

(paint outline)
(paint x-painter)
(paint diamond)
(paint wave)

效果如下:

相關文章