5b: Helpers / Design Quiz (1)

Jun 5, 2021 05:00 · 168 words · 1 minute read

問題文 🔗

Complete the design of a function called pyramid that takes a natural
number n and an image, and constructs an n-tall, n-wide pyramid of
copies of that image.

For instance, a 3-wide pyramid of cookies would look like this:

解答 🔗

;; Natural Image -> Image
;; produce a n-wide image in a row
(define (beside-image row i)
  (cond [(eq? 0 row) empty-image]
        [else (beside COOKIES (beside-image (sub1 row) i))]))
(check-expect (beside-image 0 COOKIES) empty-image)
(check-expect (beside-image 1 COOKIES) COOKIES)
(check-expect (beside-image 2 COOKIES) (beside COOKIES COOKIES))
(check-expect (beside-image 3 COOKIES) (beside COOKIES COOKIES COOKIES))

;; Natural Image -> Image
;; produce a n-row image in same col
(define COOKIES {クッキーの画像を貼り付ける})
(define (pyramid n i)
  (cond [(eq? 0 n) empty-image]
        [else (above (pyramid (sub1 n) i) (beside-image n COOKIES) )]
        ))
(check-expect (pyramid 0 COOKIES) empty-image)
(check-expect (pyramid 1 COOKIES) COOKIES)
(check-expect (pyramid 2 COOKIES)
              (above COOKIES
                     (beside COOKIES COOKIES)))
(check-expect (pyramid 3 COOKIES)
              (above COOKIES
                     (beside COOKIES COOKIES)
                     (beside COOKIES COOKIES COOKIES)))

(pyramid 5 COOKIES) を実行すると ↓ の画像が出力された。

Image from Gyazo