Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top