I'm trying to define a tree using Racket's #plai language, though I'm struggling a bit when it comes to creating the tree through an "add-node" function.
The define-type I'm using goes like this:
(define-type BBT
[empty]
[leaf (elem number?)]
[node (elem number?) (left BBT?) (right BBT?)])
And I'd like to construct a tree that looks like this:
(node 3 (empty) (node 5 (leaf 4) (leaf 6)))
Following this call:
(add-node 6 (add-node 4 (add-node 5 (add-node 3 (empty)))))
So far, I've tried the following:
(define (add-node n tree)
(match tree
[(empty) (node n (empty) (empty))]))
And that works for an empty tree, as it just adds a single node with empty trees at both sides, but I haven't found a way to construct a tree like the example I shared above.
Any tips or suggestions as to what should I do? I know I should use recursion when it catches the "node" case, but so far I haven't come up with a successful attempt.
Thanks!
From your example:
is supposed to produce
This contains many calls to
add-node, and that makes it more confusing. So to get a better idea of what you want, I'll start with the innermost call toadd-node.From the initial code in your question, it seems this should produce
So now replacing the innermost call in your larger example, it becomes
Now I have to figure out what the next-innermost call is supposed to do.
In the final output the
3stays on top and the5goes to the right node, so I can only guess that this call is supposed to produceNow replacing that call in the larger example:
The next innermost call is
Now this is where I don't understand your logic. By the pattern of the previous example, the
4should go into the rightmost node, "right-right". But in this example it seems to go in the left portion of the right node, "right-left". It doesn't seem to be going to the nearest empty node, which would be pure "left", so I don't know what pattern you're trying to make.Please clarify your question and add more specifics if you want a better answer.