Skip to content

Instantly share code, notes, and snippets.

@nh2
Created October 7, 2018 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nh2/50445ebcc3989ae297ed9e91e8c83606 to your computer and use it in GitHub Desktop.
Save nh2/50445ebcc3989ae297ed9e91e8c83606 to your computer and use it in GitHub Desktop.
Example on how to use Compact values for serialisation with GHC
#!/usr/bin/env stack
-- stack --resolver lts-11.22 script --optimize
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Data.Compact (compact, getCompact)
import Data.Compact.Serialize (writeCompact, unsafeReadCompact)
import System.Environment (getArgs)
-- Note: You cannot compact pinned values, like `ByteString`s.
-- That fails with: compaction failed: cannot compact mutable objects
type Val = [Int]
main :: IO ()
main = do
args <- getArgs
let path = "/tmp/compactfile"
case args of
["write"] -> do
let val :: Val
val = [1..1000000]
c <- compact val
writeCompact path c
["read"] -> do
eCompact <- unsafeReadCompact path
case eCompact of
Left err -> fail $ "Could not deserialise " ++ path ++ ": " ++ err
Right c -> do
let val :: Val
val = getCompact c
print (sum val)
_ -> error "bad arguments"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment