Personal tools

Compiling in constants

From HaskellWiki

Jump to: navigation, search

An example where a data structure constant is compiled into the source. To avoid excessive compilation time, we pack the structure into a bytestring literal (and gzip it for fun).

{-# LANGUAGE OverloadedStrings #-}
import Data.Binary
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as S
import Data.ByteString.Lazy
import Codec.Compression.GZip
-- this is a gzip compressed literal bytestring, storing a binary-encoded Data.Map
mytable =
    \\219\SO\194 \f\197\224\188\196\CAN\227\US\
    \\157\217\149\249< \ENQ\214\&9>\202\162\179a\
main = print =<< M.lookup "ghc" m
        -- build the table from the bytestring:
        m :: M.Map String (Maybe String)
        m = decode . decompress . fromChunks . return $ mytable

Running this:

    $ ./A
    Just "dinosaur!"

Storing the structure in C

For very large constant data, its more efficient to bypass the Haskell frontend, and store the structure in C code.

In this case, we'd take the compressed encoded structure, translate it to a C array type, then access it as a Ptr Word8 from Haskell. That Word8 Ptr can be used to build a bytestring, which can in turn be rehydrated via Data.Binary.

A full example is here: