title: How to compress the output when writing to a file?
body: <p>I have a computation that along with other things generates some data (a lot of it) and I want to write into a file.</p>
  
  <p>The way the code is structured now is (simplified):</p>
  
  <pre><code>writeRecord :: Handle -&gt; Record -&gt; IO ()
  writeRecord h r = hPutStrLn h (toByteString r)
  </code></pre>
  
  <p>This function is then called periodically during a bigger computation. It is almost like a log, and in fact, multiple files are being written simultaneously. </p>
  
  <p>Now I want the output file to be compressed with <code>Gzip</code>.
  In languages like Java I would do something like:</p>
  
  <pre><code>outStream = new GzipOutputStream(new FileOutputStream(path)) 
  </code></pre>
  
  <p>and then would just write into that wrapped output stream.</p>
  
  <p>What is the way of doing it in Haskell?
  I think writing something like </p>
  
  <pre><code>writeRecord h r = hPut h ((compressed . toByteString) r)
  </code></pre>
  
  <p>is not correct because compressing each small bit individually isn't efficient (I even tried it and the size of the compressed file is bigger than uncompressed this way).</p>
  
  <p>I also don't think that I can just produce a lazy <code>ByteString</code> (or even a list of chunks) and then write it with <code>compressed . fromChunks</code> because this will require my "generator" building the full thing in memory. And the fact that more than one file is produced at the same time makes it even more complicated.</p>
  
  <p>So what would be a way to solve this in Haskell? Writing to file(s) and have them gzipped?</p>