Created
October 7, 2018 21:25
-
-
Save nh2/50445ebcc3989ae297ed9e91e8c83606 to your computer and use it in GitHub Desktop.
Example on how to use Compact values for serialisation with GHC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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