ishan3243
ishan3243

Reputation: 1928

implementing bst in racket

I am trying to implement a bst(binary search tree) in racket. The bst is a recursive list (list x leftChild rightChild) where leftChild and rightChild are lists themselves I wrote the following code

(define (insert bst x)(
     (cond 
       [(null? bst) (append bst (list x '() '()))]
       [(<= x (car bst)) (insert (cadr bst) x)]
       [else (insert (caddr bst) x)]  
     )))

when I write

(insert (insert null 8) 9)

it gives an error: function call: expected a function after the open parenthesis, but received (list 8 empty empty) Can anyone explain this?

Upvotes: 0

Views: 2541

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

The error reported happens because there's an erroneous pair of () surrounding the cond expression, that makes Scheme try to execute a procedure when there's none. But there are several logic problems beyond that, you're not actually building a list when an element is inserted, and there's a case missing - what happens if the element already exists in the tree?. This should work:

(define (insert bst x)
  (cond 
    [(null? bst)
     (list x '() '())] ; this is the correct way to handle the base case
    [(= x (car bst))   ; this case was missing
     bst]              ; simply leave the tree as it is
    [(< x (car bst))   ; if this happens, recursively build a list
     (list (car bst) (insert (cadr bst) x) (caddr bst))] 
    [else              ; if this happens, recursively build a list
     (list (car bst) (cadr bst) (insert (caddr bst) x))]))

This is how you'd use the procedure:

(insert (insert (insert (insert null
                                10)
                        5)
                16)
        13)

=> '(10 (5 () ()) (16 (13 () ()) ()))

Upvotes: 1

Related Questions