A return value of:
State S Ret
Indicates that S is the state to carry, and Ret is the return value of the function. This makes our new version more abstract. So our tree example:
trimTreeOne'' :: Eq a => a -> Tree a -> State Bool (Tree a)
trimTreeOne'' _ Empty = return Empty
trimTreeOne'' e (Leaf x)
= if x == e
then (do put True
return Empty)
else return (Leaf x)
trimTreeOne'' e (Branch t1 t2)
= do t1' <- trimTreeOne'' e t1
haveTrimmed <- get
(if haveTrimmed
then (return (Branch t1' t2))
else (do t2' <- trimTreeOne'' e t2
return (Branch t1 t2')))And the old version as a reminder:
trimTreeOne' :: Eq a => Bool -> a -> Tree a -> (Bool, (Tree a))
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)
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)