[Haskell-cafe] Flattening tail recursion?

Robert Dockins robdockins at fastmail.fm
Fri Dec 10 11:04:24 EST 2004


Jules Bean wrote:

> 
> On 10 Dec 2004, at 15:34, Robert Dockins wrote:
> 
>> So it should get "flattened," but it still doesn't run in constant 
>> space because the "x" parmeter isn't strict, so it will accumulate a 
>> bunch of closures like (((((((0)+1)+1)+1)+1)+1).... To make it strict, 
>> do something like this:
>>
> 
> Isn't this what the strictness analyser is for? Doesn't GHC know that + 
> for Int is strict in both arguments, and therefore it shouldn't 
> accumulate a great big thunk like that?
> 
> Jules

Doesn't look like....

-------------- cnt.hs ------------------------

countlines = aux 0
   where aux x [] = x
         aux x (_:ls) = aux (x+1) ls

countlines' = aux 0
   where aux x [] = x
         aux x (_:ls)
             | x `seq` False = undefined
             | otherwise     =  aux (x+1) ls


-----------------------------------------------

$ /cygdrive/c/ghc/ghc-6.2.2/bin/ghci.exe
    ___         ___ _
   / _ \ /\  /\/ __(_)
  / /_\// /_/ / /  | |      GHC Interactive, version 6.2.2, for Haskell 98.
/ /_\\/ __  / /___| |      http://www.haskell.org/ghc/
\____/\/ /_/\____/|_|      Type :? for help.

Loading package base ... linking ... done.
Prelude> :load cnt.hs
Compiling Main             ( cnt.hs, interpreted )
Ok, modules loaded: Main.
*Main> countlines [1..100000]
100000
*Main> countlines [1..1000000]
*** Exception: stack overflow
*Main> countlines' [1..1000000]
1000000
*Main>




More information about the Haskell-Cafe mailing list