<div dir="ltr"><div class="gmail_extra"><br><div class="gmail_quote">On Tue, Aug 11, 2015 at 5:32 AM, Ben <span dir="ltr"><<a href="mailto:hyarion@iinet.net.au" target="_blank">hyarion@iinet.net.au</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">In particular, this version of <$!> wouldn't help with the lazy IO problem described in that stackoverflow question Christopher linked earlier.</blockquote></div><br></div><div class="gmail_extra">We can say more.<br><br>The version of <$!> that the SO question author himself gives as a solution to the lazy IO problem doesn't really work.<br><br></div><div class="gmail_extra">I'm referring to:<br><pre><code><span>forceM </span><span>::</span><span> Monad m </span><span>=></span><span> m a </span><span>-></span><span> m a
forceM m </span><span>=</span><span> </span><span>do</span><span> v </span><span><-</span><span> m</span><span>;</span><span> return </span><span>$!</span><span> v

</span><span>(<$!>)</span><span> </span><span>::</span><span> Monad m </span><span>=></span><span> </span><span>(</span><span>a </span><span>-></span><span> b</span><span>)</span><span> </span><span>-></span><span> m a </span><span>-></span><span> m b
f </span><span><$!></span><span> m </span><span>=</span><span> liftM f </span><span>(</span><span>forceM m</span><span>)<br><span style="font-family:arial,helvetica,sans-serif"><br></span></span></code></pre><pre><code><span><span style="font-family:arial,helvetica,sans-serif">and changing out <$> for <$!> in </span></span></code><code><span><span style="font-family:arial,helvetica,sans-serif"></span><br><br><code><span class="pln">getLines h </span><span class="pun">=</span><span class="pln"> lines </span><span class="pun"><$></span><span class="pln"> hGetContents h</span></code></span></code></pre></div><div class="gmail_extra"><br clear="all"><div><div>With the change, all of short files get read, thanks to file buffering. Like the first 4K or so. Bad surprise when you try it with longer files.<br><br></div><div>There's a right path through lazy I/O and a wrong one. Rather than take the wrong one, better the following instead:<br><br>main = mapM_ putStrLn =<< lines <$> readFile "test.txt"<br></div><div><br></div><div>But if withFile is absolutely needed (experts only):<br><br>main = withFile "test.txt" ReadMode getAndPutLines  where<br></div><div>   getAndPutLines :: Handle -> IO ()<br></div><div>   getAndPutLines h = mapM_ putStrLn =<< lines <$> hGetContents h<br><br>-- Kim-Ee</div></div>
</div></div>