0

Currently trying to wrap my head around data abstraction for binary trees in Scheme. I am following the SICP-curriculum, and looking at an implementation for a binary tree, but I am unsure of how to use it.

;; Abstraction barrier
(define (make-tree entry left right)
    (list entry left right))
(define (entry tree)
    (car tree))
(define (left-branch tree)
    (cadr tree))
(define (right-branch tree) 
    (caddr tree))

The book presents element-of-set? procedure:

(define (element-of-set? x set)
    (cond ((null? set) #f)
          ((= x (entry set)) #t)
          ((< x (entry set))
           (element-of-set? x (left-branch set)))
          ((> x (entry set))
           (element-of-set? x (right-branch set)))))

Assuming I have a tree with node 5, left-branch 1 and right-branch 9, I want to go about making the tree:

(define my-tree (make-tree 5 1 9))

Following, I want to check if 1 is a member of the set (my-tree):

(element-of-set? 1 my-tree)

Doing so yields the following error:

mcar: contract violation
expected: mpair?
given: 1

What is the correct syntax for checking if 1 is a member?

Thanks in advance.

Óscar López
  • 232,561
  • 37
  • 312
  • 386

1 Answers1

2

The problem is in the way you're building the tree, both the left and right nodes must also be trees (leafs in this case). This is the correct way to build the tree:

(define my-tree (make-tree 5
                           (make-tree 1 '() '())
                           (make-tree 9 '() '())))

Now the predicate works:

(element-of-set? 1 my-tree)
=> #t
Óscar López
  • 232,561
  • 37
  • 312
  • 386