Reputation: 22747
Suppose I have this (inserting into a BST):
mybstInsert k inp@(INode left key right)
| k < key = myNode (mybstInsert k left) key right
| k > key = myNode left key (mybstInsert k right)
What I want is, in the second condition, I want another check as well (checking if right is empty or not). So I want to break the second condition down into two conditions:
| k > key && isEmpty right == True = myNode left key (mybstInsert k right)
| k > key && isEmpty right == False = myNode left key (mybstInsert k right)
Assuming I have an isEmpty function that takes a subtree and tells me if it is empty or not.
What would be the recommended way to do this? Is this the correct syntax? (I'm working on a computer that does not have GHCi installed so I cannot check the syntax.
Upvotes: 0
Views: 93
Reputation: 80724
This is the correct syntax, but you can also simplify it a bit.
First, observe that the expression x == True
is equivalent to just x
. So you can drop the == True
.
Second, the == False
part is not necessary at all. This is because by the time you get around to checking that case, it is already known that isEmpty right == False
, because if it wasn't, you would have stopped on the previous case.
So, the whole thing can be written like this:
mybstInsert k inp@(INode left key right)
| k < key = myNode (mybstInsert k left) key right
| k > key && isEmpty right = myNode left key (mybstInsert k right)
| k > key = myNode left key (mybstInsert k right)
Finally, I'd like to point out that you're not handling the case of k == key
, so you program would crash on such input. If you wanted to include that case (and I'm assuming it would just be a no-op), then you don't have to include even the k > key
check, because by that time it would already be known that neither k == key
nor k < key
is true:
mybstInsert k inp@(INode left key right)
| k == key = inp
| k < key = myNode (mybstInsert k left) key right
| isEmpty right = myNode left key (mybstInsert k right)
| otherwise = myNode left key (mybstInsert k right)
Upvotes: 2