Haskell: Compress with GZip and write to file

Problem:

In Haskell, you want to gzip-compress a string and write it to a file.

Solution

We’ll use the zlib module for that. You might need to run

cabal install zlib

if you haven’t done that already.

Here’s the code that writes the string foobar to the gzip-compressed file foo.gz:

-- GZip compression
import qualified Codec.Compression.GZip as GZip
-- Needed to convert String literals to ByteString
import Data.ByteString.Lazy.Char8(pack)
-- ByteString.writeFile
import qualified Data.ByteString.Lazy as ByteString

main = do
       let compressedContent = pack "foobar"
       ByteString.writeFile "foo.gz" (GZip.compress compressedContent)has