如何为该代码编写测试用例?

时间:2019-04-20 02:21:52

标签: scheme racket r5rs

我刚刚开始学习树和堆,但不确定如何编写测试用例。这些代码来自我的课程幻灯片。尽管他们提供了代码,但可悲的是他们没有提供上述代码的测试用例,所以我对如何称呼它感到困惑。

我已经尝试过测试用例,例如像5这样的任何常规整数,我也尝试过使用列表进行处理,但是我遇到了错误,而且从我从图中可以看出,堆似乎是不正确的就像树的根是最小值,亚堆一样。

(define (value H)
  (car H))

(define (weight H)
  (cdr H))

(define (create-heap vw-pair left-child right-child)
  (list vw-pair left-child right-child))

(define (h-min heap)
  (car heap))

(define (left heap)
  (cadr heap))

(define (right heap)
  (caddr heap))

(define (insert vw-pair heap)
  (cond ((null? heap) (create-heap vw-pair '() '()))
        ((< (weight vw-pair) (weight (h-min heap)))
         (create-heap vw-pair (right heap) (insert (h-min heap) (left heap))))
        (else
         (create-heap (h-min heap) (right heap) (insert vw-pair (left heap))))))


(define (insert-list-of-pairs vw-pair-list heap)
  (if (null? vw-pair-list)
      heap
      (insert-list-of-pairs (cdr vw-pair-list) (insert (car vw-pair-list) heap))))


(define (remove-min heap)
  (define (combine-heaps h1 h2)
    (cond ((null? h1) h2)
          ((null? h2) h1)
          ((< (cdr (h-min h1)) (cdr (h-min h2)))
           (create-heap (h-min h1) h2 (combine-heaps (left h1) (right h1))))
          (else
           (create-heap (h-min h2)
                        h1
                        (combine-heaps (left h2) (right h2))))))
  (combine-heaps (left heap) (right heap)))

1 个答案:

答案 0 :(得分:1)

您的测试用例应确切说明您想做什么。

它们是使用代码解释所编写函数的预期用途的方式。

对于您的特定情况,我显然无法为您提供帮助,因为这正是您的代码中所缺少的:它的含义。

但是我仍然可以解释如何在Racket中编写单元测试:

;; This is a function you would write.
;; It does something, but it's not completely obvious
;; how to use it.
(define (find type basket)
  (let ([obj (assq type basket)])
    (and obj
         (cadr obj))))

;; By creating a test module, you add code that describes
;; how to use the functions in this file.
(module+ test
  (require rackunit)

  ;; This is some sample data.
  ;; It's useful to understand what kind of data
  ;; your functions are expected to process.
  (define basket '((bread baguette)
                   (fruit ananas)
                   (fruit banana)
                   (vegetable carrot)
                   (misc fork&knife)))

  ;; Here we call the function and show the expected result.
  ;; It's now clear how to use it.
  (check-equal? (find 'fruit basket) 'ananas)
  (check-equal? (find 'vegetable basket) 'carrot)
  (check-false (find 'fruit '()))
)

您可以使用raco运行这些测试:

> raco test myfile.rkt
raco test: (submod "myfile.rkt" test)
3 tests passed
相关问题