Insert node key and value in binary search tree using scheme

こ雲淡風輕ζ 提交于 2019-12-24 13:33:46

问题


I am inserting a key key and a value val into the tree-map t returning a new tree with a node containing the key and the value in the appropriate location.

I have this defined:

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

Im trying this insert method

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

I'm using this to define

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

and I'm getting this error in DrRacket

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

回答1:


What is happening is that a tree-node (which is just a list) is being returned in a position where a function is expected. Scheme cannot execute the list - it's not a function, so it's complaining.

I suspect this is because you have messed up your parentheses.

(cond (empty? t))

Is a self-contained compound expression. It is evaluated, returning the value of t. The expressions after that are not evaluated as part of the cond.



来源:https://stackoverflow.com/questions/12910579/insert-node-key-and-value-in-binary-search-tree-using-scheme

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