You need to carry state between the recursive calls. In this case, you need to know if we've trimmed an element from the left branch before trimming the right branch!
We need to add an input Bool and an output Bool.
trimTreeOne' :: Eq a => Bool -- ^Have we already trimmed an element?
-> a
-> Tree a
-> (Bool, (Tree a))
-- The first few cases are easy:
trimTreeOne' True _ t = (True, t)
trimTreeOne' False a (Leaf x)
= if x == a then (True, Empty) else (False, Leaf x)
trimTreeOne' False _ Empty = (False, Empty)
-- But branch gets complex. We optimize by not necessarily checking the 2nd branch.
trimTreeOne' False a (Branch t1 t2)
= let (answer1, trimmed1) = (trimTreeOne' False a t1)
(answer2, trimmed2) = (trimTreeOne' False a t2)
in if answer1
then (True, Branch trimmed1 t2)
else (answer2, Branch t1 trimmed2)But now our function is ugly, we wanted something with type:
trimTreeOne :: Eq a => a -> Tree a -> Tree a
So we write a wrapper function:
trimTreeOne :: Eq a => a -> Tree a -> Tree a
trimTreeOne a t = snd $ trimTreeOne' False a t
where
trimTreeOne' ...