The type is defined as
data BST = MakeNode BST String BST
| Empty
I'm trying to add a new leaf to the tree, but I don't really understand how to do it with recursion.
the function is set up like this
add :: String -> BST -> BST
The advantage of using binary trees is that you only need to look at the "current part" of the tree to know where to insert the node.
So, let's define the add function:
add :: String -> BST -> BST
If you insert something into an empty tree (Case #1), you just create a leaf directly:
add s Empty = MakeNode Empty s Empty
If you want to insert something into a node (Case #2), you have to decide which sub-node to insert the value in. You use comparisons to do this test:
add s t@(MakeNode l p r) -- left, pivot, right
| s > p = Node l p (add s r) -- Insert into right subtree
| s < p = Node (add s l) p r -- Insert into left subtree
| otherwise = t -- The tree already contains the value, so just return it
Note that this will not rebalance the binary tree. Binary tree rebalancing algorithms can be very complicated and will require a lot of code. So, if you insert a sorted list into the binary tree (e.g. ["a", "b", "c", "d"]), it will become very unbalanced, but such cases are very uncommon in practice.
@ symbol creates a name for the whole pattern to the right of it. So, if I do t @ (MakeNode l p r), it's like saying let t = MakeNode l p r in in the code that follows, except that the program won't create a new MakeNode; it will just reuse the old one.
BSTwon't work. I think you meandata BST = MakeNode String BST BST | Empty, right?