如何使此代码适用于矩形?(方案/打字球拍)



这是我写的代码,函数的作用是:使用一个图像列表(aloim(和一个正数n。它产生;aloim中的第一个图像不是n乘n的正方形;如果不能;找到这样一个图像,它会产生#false我已经让它只适用于正方形,但如果我在图像列表中添加一个矩形,它就不起作用,我也不知道如何修复它。如果有人能给我指明正确的方向,那就太棒了!

#lang typed/racket
(require typed/test-engine/racket-tests)
(require typed/2htdp/image)
(require typed/2htdp/universe)
(define-type ImageOrFalse (U Image Boolean))
(: ill-sized : (Listof Image) Integer -> ImageOrFalse)
; Consumes a list of images aloim and a positive number n. It produces
; the first image in aloim that is not an n by n square; if it cannot
; find such an image, it produces #false
(define A (square 10 "solid" "blue"))
(define B (square 30 "solid" "red"))
(define C (square 15 "solid" "black"))
(define D (square 20 "solid" "black"))
(define ListA (cons A (cons B '())))
(define ListB (cons B (cons C '())))
(define ListC (cons A '()))
(define ListD (cons A (cons B (cons C (cons D '())))))
(define ListE '())
(define (ill-sized aloim n)
(cond [(empty? aloim) #false]
[(cons? aloim)
(if (and
(not (eq? (image-width (first aloim)) n))
(not (eq? (image-height (first aloim)) n)))
(first aloim)
(ill-sized (rest aloim) n))]))

(check-expect (ill-sized ListA 10) B)
(check-expect (ill-sized ListB 10) B)
(check-expect (ill-sized ListC 10) #false)
(check-expect (ill-sized ListD 20) A)
(check-expect (ill-sized ListE 30) #false)

(test)

我认为您输入了错误的检查预期输出。我在这里使用#lang racket,我认为没有什么不同。

如果您只想检查square,只需使用filter删除所有rectangle,然后将列表发送到ill-sized

#lang racket
(require test-engine/racket-tests)
(require 2htdp/image)
(require 2htdp/universe)
(define (ill-sized aloim n)
(cond
[(empty? aloim) #false]
[(or (= n (image-width (first aloim)))
(= n (image-height (first aloim))))
(first aloim)]
[else
(ill-sized (rest aloim) n)]))

(define (square-side=n aloim n)
(local [(define (square? img)
(= n (image-width img) (image-height img)))]
(ill-sized (filter square? aloim) n)))
;;; TEST
(define A (square 10 "solid" "blue"))
(define B (square 30 "solid" "red"))
(define C (square 15 "solid" "black"))
(define D (square 20 "solid" "black"))
(define E (rectangle 40 20 "outline" "black"))
(define F (rectangle 20 50 "solid" "blue"))
(define list-of-images (list A B E F C D))
(check-expect (ill-sized list-of-images 60) #false)
(check-expect (ill-sized list-of-images 20) E)
(check-expect (ill-sized list-of-images 50) F)
(check-expect (square-side=n list-of-images 20) D)
(test)

最新更新