[Haskell-cafe] problem with IO, strictness, and "let"

Bulat Ziganshin bulat.ziganshin at gmail.com
Fri Jul 13 03:05:57 EDT 2007


Hello Michael,

Friday, July 13, 2007, 8:22:09 AM, you wrote:

>         cs <- return $! lines c
>         hClose h
>         putStrLn $ show $ length cs

> This works.  However, I don't understand why this version works and the previous version doesn't.
> Can anyone walk me through the evaluation?  Also, is there a way to make "let" strict?

first, it may be written also as

>         return $! lines c
>         hClose h
>         let cs = lines c
>         putStrLn $ show $ length cs

the key is that return is *action* and should be executed before doing
next action, hClose. '$!' means that argument should evaluated before
calling 'return', so 'return $!' is a sort of idiom that force
immediate evaluation of its argument (but be cautious! for list it
evaluates only its first element and you program actually always
prints 1 for non-empty file! the right solution will be to force
evaluation of whole list by calculating its 'length' or 'last', for
example)

as usual, i suggest you to read http://haskell.org/haskellwiki/IO_inside


-- 
Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com



More information about the Haskell-Cafe mailing list