[Haskell-cafe] Flattening tail recursion?

Stefan Holdermans sholderm at students.cs.uu.nl
Fri Dec 10 10:32:17 EST 2004


Will,

>    countLines [] = 0
>    countLines (_:ls) = 1 + countLines ls
>
> I would have thought that this was tail recursive and would be
> flattened into iteration by the compiler. Can anyone explain why? Is
> it because the call is embedded in an expression?

This is the tail-recursive version:

\begin{code}
   countLines = countLines' 0
     where countLines' k []       = k
           countLines' k (l : ls) = countLines' (k + 1) ls
\end{code}

See, for example, http://www.haskell.org/hawiki/TailRecursive.

HTH,

Stefan



More information about the Haskell-Cafe mailing list