scheme determine a string inside a tree list or not

戏子无情 提交于 2019-12-13 04:48:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!