我在Dr Racket写了那段代码,但我不知道为什么,但我的上一次测试不起作用。任何人都知道为什么?

时间:2014-12-05 08:33:17

标签: scheme racket

我在Dr Racket写了这个代码,我必须评估所有项目,目标是选择哪个更好买。现在我想我可能会被捕,但现在我对上一次测试有问题,这是Code中最后一行的测试。不知怎的,它没有布线,任何人都可能知道我的代码有什么问题。也许我太过分了,但我找不到我的错误。

对于答案,我会非常感激。

    (define-struct item (name volume yield typical))

;; volume of a standard european container in m^3
(define container-volume 78.6)

;; sample items
(define strong-beer (make-item "Strong Beer" 15 8372 7))
(define cheap-beer (make-item "Cheap Beer" 21 4562 2))
(define good-beer (make-item "Good Beer" 7 5113 9))
(define pretzels (make-item "German Style Pretzels" 7 9280 5))
(define weisswurst (make-item "Weisswurst" 8 7254 10))
(define sweet-mustard (make-item "Sweet Mustard" 1 265 6))
(define haxen (make-item "Haxen" 11 3500 7))
(define sauerkraut (make-item "Sauerkraut" 7 4012 3))
(define bavarian-leberkaes (make-item "Bavarian Leberkaes" 6 1952 6))
(define schnitzel (make-item "Schnitzel" 16 8068 2))
(define obatzda (make-item "Obatzda" 3 3025 8))
(define dumplings (make-item "Dumplings" 8 1234 3))
(define dirndl (make-item "Dirndl" 12 8069 9))

;; all items
(define all-stuff
  (list strong-beer cheap-beer good-beer pretzels weisswurst sweet-mustard
        haxen sauerkraut bavarian-leberkaes schnitzel obatzda dumplings dirndl))


;;Code:
(define (evaluate-item-sum item)
  (foldr (lambda (item sum) (+ (item-volume item) sum)) 0 item)
  )

;;Test:
(check-expect (evaluate-item-sum all-stuff) 122)
(check-expect (evaluate-item-sum (list haxen dirndl)) 23)

;;===============================================================================


;;Code:
(define (choose-items items container-volume)
  (cond
    ((empty? items) empty)
    ((cons? items)
     (local (
             (define first-volume (item-volume (first items))))
             (if (> first-volume container-volume)
             (choose-items (rest items) container-volume)
             (local (
                     (define choice1 (choose-items (rest items) container-volume))
                     (define choice2
                       (cons (first items)
                             (choose-items (rest items) (- container-volume first-volume)))))
               (if (> (evaluate-item-sum choice1) (evaluate-item-sum choice2))
                   choice1
                   choice2)))))))



;; Tests
(check-expect (choose-items all-stuff 50) (list haxen dirndl))

1 个答案:

答案 0 :(得分:0)

你在choose-items的调用中使用值50,但我猜它应该是23.然后,还有第二个组合(StrongBeer GoodBeer Mustard),所以要得到你想要的结果' d必须将Haxen和Dirndl移到列表all-stuff的前面,以便首先找到它们。使用该修改后的列表和值23,最后一次测试通过:

(define all-stuff
  (list haxen dirndl strong-beer cheap-beer good-beer pretzels weisswurst sweet-mustard
         sauerkraut bavarian-leberkaes schnitzel obatzda dumplings ))

(check-expect (choose-items all-stuff 23) (list haxen dirndl))