方案确定树列表中的字符串与否 [英] scheme determine a string inside a tree list or not

查看:59
本文介绍了方案确定树列表中的字符串与否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数据定义,

(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?

推荐答案

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

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)

这篇关于方案确定树列表中的字符串与否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆