Question

I am completely new to Scheme and functional languages in general. I am trying to create 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. I have a "make" function, which creates an empty tree: ( () () () ). I also have the insert function. Here is the code:

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

To test it, I run the following lines:

> (define b1 (make))
> (define b2 (insert b1 1))
> b2
(1 (() () ()) (() () ()))
> (define b3 (insert b2 2))

I then receive the following error:

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

I have checked and re-checked my parentheses...and running it in debug mode, I see it fails at the END of inserting 2 into the tree. Until the, it works as planned. Is this the cause of a foolish syntax/logic error on my part?

Était-ce utile?

La solution

((list (car t) ((insert (cadr t)  x)) (caddr t)))

The outer pair of parentheses is the problem here. (list (car t) ((insert (cadr t) x)) (caddr t)) gives you a list. By wrapping another pair of parentheses around it, you're trying to apply that list as if it was a function, which you can't - thus the error message.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top