I am trying to traverse a tree in Haskell where the idea is to return a new tree that satisfies a predefined condition. If a node's value x >= a and x < b, then this node should be included in the new tree. I must be able to traverse the entire tree and all branches to make sure that all valid nodes are included.
However, now I am struggling to come up with a solution on how to traverse both left and right branch when the precondition is not met in a node.
For example for a = -5 and b = 0 so that -5 <= x <0 :
3
/ \
-12 8
/ \
1 -5
Should return -5. So the solution should just discard any node not meeting the precondition, and if the precondition is met, it should add that node to the new tree.
This code is what I got so far.
data Tree = Void | Node Tree Integer Tree
deriving (Eq, Show)
nextTree :: Integer -> Integer -> Tree -> Tree
nextTree _ _ Void = Void
nextTree a b (Node Void x Void) = if x >= a && x < b then Node Void x Void else Void
nextTree a b (Node l x Void) = if x >= a && x < b then Node (nextTree a b l) x Void else nextTree a b l
nextTree a b (Node Void x r) = if x >= a && x < b then Node Void x (nextTree a b r) else nextTree a b r
nextTree a b (Node l x r)
| x >= a && x < b = Node (nextTree a b l) x (nextTree a b r)
| not (x >= a && x < b) = undefined
| otherwise = undefined
It is where undefined is written that I need some way to traverse both left and right branch and then return next subtree to nextTree. I a just do
| not (x >= a && x < b) = nextTree (a b r)
it will only traverse the right branch. I would like to to something like
| not (x >= a && x < b) = nextTree (a b r) && nextTree (a b r)
But I am not sure how to do it in Haskell. Or if it is even possible?
case (nextTree a1 b1 r1, nextTree a2 b2 r2) of (Void, Void) -> ... ; (Void, Node ...) -> ; ...