简体   繁体   中英

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

I am a noob at 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: ( () () () ). 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)))

You only want to call as-list on trees, and the car of your t is not a tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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