Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>hGetContents</code> uses lazy IO; it only reads from the file as you force more of the string, and it only closes the file handle when you evaluate the entire string it returns. The problem is that you're enclosing it in <code>withFile</code>; instead, just use <code>openFile</code> and <code>hGetContents</code> directly (or, more simply, <code>readFile</code>). The file will still get closed once you fully evaluate the string. Something like this should do the trick, to ensure that the file is fully read and closed immediately by forcing the entire string beforehand:</p> <pre><code>import Control.Exception (evaluate) readCode :: FilePath -&gt; IO Code readCode fileName = do text &lt;- readFile fileName evaluate (length text) return (parseCode text) </code></pre> <p>Unintuitive situations like this are one of the reasons people tend to avoid lazy IO these days, but unfortunately you can't change the definition of <code>hGetContents</code>. A strict IO version of <code>hGetContents</code> is available in the <a href="http://hackage.haskell.org/package/strict" rel="noreferrer">strict</a> package, but it's probably not worth depending on the package just for that one function.</p> <p>If you want to avoid the overhead that comes from traversing the string twice here, then you should probably look into using a more efficient type than <code>String</code>, anyway; the <code>Text</code> type has <a href="http://hackage.haskell.org/packages/archive/text/latest/doc/html/Data-Text-IO.html" rel="noreferrer">strict IO equivalents</a> for much of the <code>String</code>-based IO functionality, <a href="http://hackage.haskell.org/packages/archive/bytestring/latest/doc/html/Data-ByteString.html#g:26" rel="noreferrer">as does <code>ByteString</code></a> (if you're dealing with binary data, rather than Unicode text).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload