Originally Posted by

**R.B.**
Is there a better way of doing this?

First off, you don't need Ord. All you need is Eq.

Code:

search :: Eq a => a -> (Tree a b) -> Bool
search y = search'
where
search' Empty = False
search' (Leaf x _) = x == y
search' (Node _ left right) = search' left || search' right

One issue with your desired second version of search comes in the case where the value is found nowhere in the tree. For example, a tree with only Empty nodes at its end, or simply a tree filled with values not that value. What you probably need to do is use Maybe (or rather any MonadPlus instance).

Maybe version (less general)

Code:

search :: Eq a => a -> (Tree a b) -> Maybe b
search a = search'
where
search' Empty = Nothing
search' (Leaf a' b) = if a == a'
then Just b
else Nothing
search' (Node _ left right) = case search' left of -- NOTE: can be done using mplus
Nothing -> seach' right
Just b -> Just b

MonadPlus version (more general)

Code:

search :: (MonadPlus m, Eq a) => a -> (Tree a b) -> m b
search a = search'
where
search' Empty = mzero
search' (Leaf a' b) = if a == a'
then return b
else mzero
search' (Node _ left right) = search' left `mplus` search' right

Note you can define the Bool version of the function using this new search function.

Code:

import Data.Maybe (isJust)
dot = (.).(.)
searchBool :: Eq a => a -> (Tree a b) -> Bool
searchBool = isJust `dot` seach

As a side note, people camelCase (CamelCase) in Haskell. They dont_use_underscores (DONT_USE_UNDERSCORES).

## Bookmarks