简体   繁体   English

方案错误,将二进制搜索树作为有序列表(R5RS)返回

[英]Scheme Error, Return Binary Search Tree as Ordered List (R5RS)

I am a noob at Scheme. 我是Scheme的菜鸟。 I have a binary search tree. 我有一个二叉搜索树。 The format of a node is a list of three elements, the first being the value at the node, the second being the left child node, and the third being the right child node. 节点的格式是三个元素的列表,第一个是该节点上的值,第二个是左子节点,第三个是右子节点。 The "make" function creates an empty tree that looks like this: ( () () () ). “ make”函数创建一个空树,如下所示:(()()())。 I am able to create the tree, insert values, and find if a certain value exists in the tree. 我能够创建树,插入值并查找树中是否存在某个值。 My problem comes when I try to write a function that returns the tree as an ordered list. 当我尝试编写将树作为有序列表返回的函数时,我的问题就来了。 Insert and Make functions: 插入和制作功能:

;Inserts a number into the tree
(define (insert t x)
    (cond ((null? (car t))
          (list x (make) (make)))
          ((< x (car t))
           (list (car t) (insert (cadr t)  x) (caddr t)))
          ((> x (car t))
           (list (car t) (cadr t) (insert (caddr t) x) ))


    )
)

;Makes a new empty tree
(define (make)
    (list (list) (list) (list))
 )

Those works fine. 那些工作正常。 Here is my as-list: 这是我的清单:

;Gives list of all numbers
(define (as-list t)
    (cond
         (
           (null? (car t) )
           (list)
         )
          (
           #t
           (append (as-list (cadr t)) (as-list (car t)) (as-list (caddr t)))
         )
     )
  )

Running this, I get a contract violation, saying it expected "mpair?". 运行此命令,我遇到合同违规,说它期望“损害赔偿?”。 I do not believe this is a logic error on my part, but it may be. 我不认为这是我的逻辑错误,但可能是。 Is this another parentheses problem? 这是另一个括号问题吗?
Thank you for your time! 感谢您的时间!

Your recursion should be 您的递归应该是

(append (as-list (cadr t)) (list (car t)) (as-list (caddr t))) (追加(清单(cadt t))(清单(car t))(清单(caddr t)))

You only want to call as-list on trees, and the car of your t is not a tree. 您只想按树上的名称进行调用,而您的汽车不是树。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM