I’m having issues writing a function to walk through a binary tree, the function takes in a search_term, list and returns true or false. Here is what I have and it’s essentially the same thing I found googling how to implement binary search in Scheme.
(define (tree-lookup val tree)
(if (empty-tree? tree)
#f
(let ((curr-val (node-value tree))
(left (node-left tree))
(right (node-right tree)))
(cond ((equal? val curr-val) #t)
((< val curr-val))
(tree-lookup val left)
(else
(tree-lookup val right))))))
(define tree-test '(((1 2) 3)(4 (5 6)) 7 (8 9 10))) ; Test tree
The problem comes when it tries to compare the “val” variable with the node. This means I am comparing a real number to a list, like (< 2 ‘((1 2) 3)). I tried testing for atom values only but then I am stuck on how to go back up the tree when I reach a leaf.
Here’s the error message:
<: contract violation
expected: real?
given: '{{1 2} 3}
argument position: 2nd
other arguments...:
8
At first glance the procedure looks fine. I suspect that the problem is in the
node-value,node-leftandnode-rightprocedures, or in the way you’re building the tree – for starters, the sample tree provided in the question doesn’t seem right to me.Think about it, the error message signals that the
<operator was applied to the list'{{1 2} 3}, meaning thatcurr-valis a list, but it should be a value.