scheme确定树列表中的字符串与否

时间:2014-10-30 20:34:31

标签: scheme racket

这是我的数据定义,

(define-struct leaf ())

;; interpretation: represents a leaf on a BT, a node with no children

(define-struct node (word left right))

;; interpretation: represents a node on a BT with a word, a left and a right 
;; subtree

;; A BinaryTree (BT) is one of 
;; - (make-leaf)
;; - (make-node String BT BT)

;; bt-has? : BT String -> Boolean
;; given a BT tree and a String w and returns true if w is in the tree 
;; and false otherwise

(define (bt-has? tree w)
(cond 
   [(leaf? tree) (bt-has? tree w)]
   [(and (node? tree)
         (string=? w (node-word (first tree))))
    (bt-has?  (rest tree) w) ]))

我不知道为什么它一直给出所有问题的结果都是错误的错误代码。

(string=? w (node-word (first tree))))

对我来说似乎是对的。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我猜我犯的错误是BT(树)是一个不是列表的结构,所以这就是为什么这个错误代码会弹出。 这是修订版。

;; bt-has? : BT String -> Boolean
;; given a BT tree and a String w and returns true if w is in tree 
;; and false otherwise

(define (bt-has? tree w)
   (cond 
      [(leaf? tree) false]
      [else
          (and (node? tree)
               (string=? w (node-word tree))
               (bt-has? (node-left tree) w)
               (bt-has? (node-right tree) w))]))

 ;; tests 

    (check-expect (bt-has?  (make-node "a" (make-leaf) (make-node "b" (make-leaf) (make-leaf) "a")) true)
    (check-expect (bt-has?  (make-node "a" (make-leaf) (make-leaf)) "b")false)
    (check-expect (bt-has?  (make-leaf) "a") false)