Personal tools

Compiling in constants

From HaskellWiki

Revision as of 04:47, 25 February 2008 by DonStewart (Talk | contribs)

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!"