2

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?

Ryan C. Stacy
  • 87
  • 1
  • 7

1 Answers1

4
((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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 2
    Thank you so much! I had a feeling it was a stupid mistake on my part. Worked like a charm. I guess the whole "When in doubt, add more parentheses" doesn't apply here. – Ryan C. Stacy Sep 13 '12 at 01:29
  • 2
    @Ryan You know how Python is indentation-sensitive, and Ruby is whitespace-sensitive? Lisp and Scheme are parentheses-sensitive. – C. K. Young Sep 13 '12 at 01:57