For now I have the tree data type:
data TernaryTree a = EmptyTree
| Node a (TernaryTree a) (TernaryTree a) (TernaryTree a)
deriving (Show)
And I am trying to create a function that can loop up a value in the Ternary Tree. The tree is not sorted.
treeLook :: (Ord a)=> a -> TernaryTree a -> Bool
treeLook x EmptyTree = False
treeLook x (Node a left mid right) =
if x /= a
then do
treeLook x left
treeLook x mid
treeLook x right
else
True
I have this for now but I can't compile it. It says:
Couldn't match expected type "m0 b0" with actual type "bool" on the line:
treeLook x right
dois a keyword that is used to enable some syntactical sugar for monads. In this sitation, there is no need for monads.There are two cases here: the
EmptyTreethat means that we failed to find the value, so we returnFalse.For the
Nodewe can check up to four conditions: is the value the value we look for, is the value in the first subtree, is the value in the second subtree, and is the value in the third subtree. From the moment one of the checks isTrue, we can returnTrue. If all checks fail, we returnFalse, this is the behavior of a logical or (||). So we can write it like:Or we can define a locally scoped function preventing us from recursively passing the value we are looking for:
Note that since the tree is not sorted, we do not need the
Ord atype constraint, we only need to check equality (here inx == a), so theEq atype constraint is sufficient.