【问题标题】:Insert node key and value in binary search tree using scheme使用方案在二叉搜索树中插入节点键和值
【发布时间】:2012-10-16 08:34:53
【问题描述】:

我将一个键 key 和一个值 val 插入到树形映射 t 中,返回一个新树,其中一个节点包含相应位置的键和值。

我已经定义了:

(define (tree-node key value left right)(list key value left right))

(define (get-key tn) (node_key tn))
(define (get-val tn) (node_val tn))
(define (get-left tn) (node_left tn))
(define (get-right tn) (node_right tn))

(define (node_key tn) (list-ref tn 0))
(define (node_val tn) (list-ref tn 1))
(define (node_left tn) (list-ref tn 2))
(define (node_right tn) (list-ref tn 3))

我正在尝试这种insert 方法

(define (insert t key val)

  (cond (empty? t))
  (tree-node (key val '() '()))

  ((equal key (get-key t))
   (tree-node (key val (get-left t) (get-right t)))

   ((<key (get-key t))
    (tree-node ((get-key t) (get-val t) (insert (get-left t key val)) (get-right t)))
    (tree-node ((get-key t) (get-val t) (get-left t) (insert (get-right t key val)))))))

我用这个来定义

(define right (insert (insert empty 3 10) 5 20))

我在 DrRacket 中遇到了这个错误

application: not a procedure;
expected a procedure that can be applied to arguments
given: (list 0 1 2)
arguments...: [none]

【问题讨论】:

    标签: scheme racket binary-search-tree


    【解决方案1】:

    正在发生的事情是一个树节点(它只是一个列表)正在返回到预期函数的位置。 Scheme 无法执行该列表 - 它不是一个函数,所以它在抱怨。

    我怀疑这是因为你把括号弄乱了。

    (cond (empty? t))
    

    是一个自包含的复合表达式。它被评估,返回 t 的值。之后的表达式不会作为条件的一部分进行评估。

    【讨论】:

    • 这里有很多语法错误。代码中树节点的使用在语法上也很可疑。作者需要确保传递四个参数。目前,代码表示它正在给它一个参数。在这类语言中调用函数是(function arg1 arg2 ...),而不是function(arg1 arg2 ...)
    • 我重新缩进了原始发帖人的问题。缩进级别应该清楚地表明程序结构是扭曲的。例如,属于cond 的东西在cond 之外。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多