[Haskell-cafe] Expanding do notation

Chris Kuklewicz haskell at list.mightyreason.com
Sat Jan 7 12:28:37 EST 2006


Josef Svenningsson wrote:
> 
> 
> On 1/7/06, *Chris Kuklewicz* <haskell at list.mightyreason.com
> <mailto:haskell at list.mightyreason.com>> wrote:
> 
>     When you put "print (head p)" at then end, it keeps a reference to the
>     whole list "p" which is your space leak.  If you want to store the head
>     of p, this *should* work:
> 
>     > main = do n <- getArgs >>= return . read . head
>     >           let p = permutations [1..n]
>     >           headOfP <- return (head p)
>     >           mapM_ (putStrLn . concatMap show) $ take 30 p
>     >           putStr $ "Pfannkuchen(" ++ show n ++ ") = "
>     >           putStrLn . show $ foldl' (flip (max . steps 0)) 0 p
>     >           print headOfP
> 
>     The "headOfP" is computed as an IO action at that point in the program,
>     so "headOfP" does not hold a reference to "p" as a whole. 
> 
> 
> Without having tried this I'd say that you should use
> Control.Excection.evaluate instead of 'return'. Or you could use 'seq'.
> I suspect that otherwise the 'head p' will not be evaluated until the
> last line and you will have the same problem as before.
> 
> Cheers,
> 
> /Josef

Thanks Josef.

headOfP <- return $! (head p)

headOfP <- (head p) `seq` return (head p)

headOfP <- return (Control.Excection.evaluate (head p))

Are strict enough to do the trick.


More information about the Haskell-Cafe mailing list