This time around, Programming Praxis here (make sure you download pmatch as well).
First, we need to provide tree functions that are designed to work on complete binary trees, taking the size as an additional parameters.
; lookup an item in a balanced binary tree (define (tree-lookup size tr i) (pmatch (list size tr i) [(,size (Leaf ,x) 0) x] [(,size (Leaf ,x) ,i) (error 'tree-lookup "subscript-error")] [(,size (Node ,x ,t1 ,t2) 0) x] [(,size (Node ,x ,t1 ,t2) ,i) (let ([size^ (div size 2)]) (if (<= i size^) (tree-lookup size^ t1 (- i 1)) (tree-lookup size^ t2 (- i 1 size^))))])) ; update a balanced binary tree with a new element (define (tree-update size tr i y) (pmatch (list size tr i y) [(,size (Leaf ,x) 0 ,y) `(Leaf ,y)] [(,size (Leaf ,x) ,i ,y) (error 'tree-update "subscript error")] [(,size (Node ,x ,t1 ,t2) 0 ,y) `(Node ,y ,t1 ,t2)] [(,size (Node ,x ,t1 ,t2) ,i ,y) (let ([size^ (div size 2)]) (if (<= i size^) `(Node ,x ,(tree-update size^ t1 (- i 1) y) ,t2) `(Node ,x ,t1 ,(tree-update size^ t2 (- i 1 size^) y))))])) With that, we have everything we need to represent the lists.
read more...