[Haskell-cafe] Re: Understanding tail recursion and trees

Felipe Lessa felipe.lessa at gmail.com
Thu May 1 08:44:43 EDT 2008


On Thu, May 1, 2008 at 9:32 AM, Edsko de Vries <devriese at cs.tcd.ie> wrote:
>  So then the question becomes: what *is* the best way to write this function?

I guess it would be simpler to have the counter on the data type and a
smart branch constructor:

> data Tree = Leaf Integer | Branch Integer Tree Tree
>
> count :: Tree -> Integer
> count (Leaf _)       = 1
> count (Branch c _ _) = c
>
> branch :: Tree -> Tree -> Tree
> branch left right = Branch (count left + count right) left right
>
> gentreeL :: Integer -> Tree
> gentreeL 0 = Leaf 0
> gentreeL n = branch (gentreeL (n-1)) (Leaf 0)

etc.

-- 
Felipe.


More information about the Haskell-Cafe mailing list