问题
Here's my data definition,
(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) ]))
I don't know why it keeps giving the all question results were false error code.
(string=? w (node-word (first tree))))
seems right to me. Any suggestion?
回答1:
I guess the mistake i made was BT(tree) is a structure not a list so that's why this error code pops. Here's a revised version.
;; 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)
来源:https://stackoverflow.com/questions/26662745/scheme-determine-a-string-inside-a-tree-list-or-not