【问题标题】:implementing bst in racket在球拍中实施 bst
【发布时间】:2013-11-08 14:44:32
【问题描述】:

我正在尝试在球拍中实现 bst(二叉搜索树)。 bst 是一个递归列表 (list x leftChild rightChild) 其中 leftChild 和 rightChild 是列表本身 我写了以下代码

(define (insert bst x)(
     (cond 
       [(null? bst) (append bst (list x '() '()))]
       [(<= x (car bst)) (insert (cadr bst) x)]
       [else (insert (caddr bst) x)]  
     )))

当我写作时

(insert (insert null 8) 9)

它给出一个错误:函数调用:期望在左括号后有一个函数,但收到了(列表 8 为空) 谁能解释一下?

【问题讨论】:

  • 您是否将list 定义为不是文件前面的函数的东西?此外,cond 周围还有一对额外的括号。一般来说,如果您没有发布足够的上下文来重现您的问题(例如,您使用的是什么语言设置?),则很难给您反馈

标签: functional-programming scheme racket binary-search-tree


【解决方案1】:

报告的错误发生是因为cond 表达式周围有一对错误的(),这使得Scheme 在没有过程时尝试执行一个过程。但是除此之外还有几个逻辑问题,当插入一个元素时,您实际上并没有构建一个列表,并且缺少一个案例 - 如果该元素已经存在于树中会发生什么?这应该有效:

(define (insert bst x)
  (cond 
    [(null? bst)
     (list x '() '())] ; this is the correct way to handle the base case
    [(= x (car bst))   ; this case was missing
     bst]              ; simply leave the tree as it is
    [(< x (car bst))   ; if this happens, recursively build a list
     (list (car bst) (insert (cadr bst) x) (caddr bst))] 
    [else              ; if this happens, recursively build a list
     (list (car bst) (cadr bst) (insert (caddr bst) x))]))

这是您使用该过程的方式:

(insert (insert (insert (insert null
                                10)
                        5)
                16)
        13)

=> '(10 (5 () ()) (16 (13 () ()) ()))

【讨论】:

  • 哦,我明白了!我对球拍比较陌生,所以谢谢你的帮助
  • @ishan3243 没问题,我的荣幸:)
  • 顺便说一句 b/w (list 1 2 3 (list 1 2 3)) 和 '(1 2 3 '(1 2 3)) 有什么不同
  • @ishan3243 不,它们是一样的
  • @ishan3243 对不起,我的错。仅当您删除内部引号时它们才会相同(这是不必要的),否则它们是不同的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 2014-03-23
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多