Search code examples
lambdaschemelisp

Exception in car: () is not a pair


I have this program I have to make:

enter image description here

I've been able to make a program that correctly figures out if something exists in the tree, but it breaks if something ISN'T in the tree. enter image description here

enter image description here The debug message isn't helpful at all. The only place I ever use car is in the 3 auxiliary functions. Can someone explain what this means/what I should do? I've been tinkering around and can't find a fix.

The following is what I have so far:

(define (val T)
    (car T)
)

(define (left T)
    (car (cdr T))
)

(define (right T)
    (car (cdr (cdr T)))
)

(define (tree-member-helper? V T)
    (if (not (null? (val T)))

        (if (< V (val T))
            (tree-member-helper? V (left T))
            (if (> V (val T))
                (tree-member-helper? V (right T))
                 #t
            )
        )
        '()
    )
)

Solution

  • In this part:

    (not (null? (val T)))
    

    You are checking if the value is not null. A typical iteration of a tree one checks if the value is the empty tree or not. In your case () since the node (1 () ()) is a node with value 1 and no empty trees as children.

    First when you have established that the node is not empty you can do car and cdr on them (or call functions that do that).

    Now why do we expect caddr to work without checking you might ask. Well if you send a invalid tree like '(1 (2) (3)) it doesn't and you get a similar error. You could fix this by making a function that checks that the node is indeed valid:

    (define (valid-node? node)
      (and (list? node)
           (= (length node) 3)
           (number? (car node))))