[Haskell-cafe] Possible Improvements

Stefan O'Rear stefanor at cox.net
Mon Dec 3 00:26:02 EST 2007

On Mon, Dec 03, 2007 at 05:20:35AM +0000, PR Stanley wrote:
> Hi
> data Tree = Leaf Int | Node Tree Int Tree
> occurs :: Int -> Tree -> Bool
> occurs m (Leaf n) = m == n
> occurs m (Node l n r) = m == n || occurs m l || occurs m r
> It works but I'd like to know if it can be improved in any way.
> Thanks, Paul

Note that occurs checks elements in pre-order; so it can be factored
into preorder and elem, where elem is defined in the Prelude:

preorder (Leaf n) = [n]
preorder (Node l n r) = n : preorder l ++ preorder r

occurs x = elem x . preorder


Also, Tree can be made to work on any type of value as a type

data Tree k = Leaf k | Node (Tree k) k (Tree k)

-- definitions of preorder and occurs are the same as before

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20071202/038b2a35/attachment.bin

More information about the Haskell-Cafe mailing list