[Haskell-cafe] Re: Newbie request

Chad Scherrer chad.scherrer at gmail.com
Fri Jun 9 13:21:55 EDT 2006


Philip,

you wrote:
-------------------------------------------------------------------------------------
I am trying to learn Haskell. As an exercise, I wrote a
function to create a binary tree in level-order. I am attaching
the code. I am sure there are a number of places where
the code could be improved. Could you please point these out?

Thanks,
Philip

>countNodes :: Tree a -> Integer
>countNodes Empty = 0
>countNodes (Tree rootNode left right) = 1 + countNodes left
                                               + countNodes right
--------------------------------------------------------------------------------------
Stylistically, this is usually written using a fold. Try writing a function

fold :: (a -> b -> b -> b) -> b -> Tree a -> b

Then rewrite countNodes as

countNodes = fold f 0 where f x left right = 1 + left + right

A huge number of other handy functions can then be written in terms of fold.

-- 

Chad Scherrer

"Time flies like an arrow; fruit flies like a banana" -- Groucho Marx
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org//pipermail/haskell-cafe/attachments/20060609/026dd99b/attachment.htm


More information about the Haskell-Cafe mailing list