[Haskell] Simple and Easy Persistence
Donald Bruce Stewart
dons at cse.unsw.edu.au
Tue Dec 6 21:39:59 EST 2005
I usually use the the Binary class, found in NewBinary for this task.
You derive Binary for each type you wish to serialise, which gives you a
get and put function on handles. A stripped down version suitable for
many tasks lives here:
http://www.cse.unsw.edu.au/~dons/code/hmp3/Binary.hs
This is the same class GHC uses to read and write .hi files.
Some info on this at http://www.haskell.org/hawiki/BinaryIo, and
ftp://ftp.cs.york.ac.uk/pub/malcolm/ismm98.html
Examples of a persistent database here:
http://www.cse.unsw.edu.au/~dons/code/hmp3/Tree.hs
and here
http://www.cse.unsw.edu.au/~dons/code/lambdabot/Plugins/Seen.hs
I actually think a derivable class Binary is simple and solid enough it
should be in the standard libs..
-- Don
mmm92:
> Hi all,
>
> I have some program data that I'd like to persist. I could just
> use read and show and file I/O to store arrays as files. [1] This
> works and it is easy and simple (which I like) but it is also
> inefficient and a little cumbersome.
>
> I imagine that this is a very common task, and I know of utilities
> in other environments like object databases, embedded databases, XML
> persistence, etc. that can make this kind of persistence simple *and*
> relatively efficient and reliable. E.g.) I have found the HSQLDB
> embedded database [2] to be useful when writing Java applications.
> What do you do for quick and easy persistence in Haskell? Are there
> any libraries or techniques that are especially useful for this?
>
> [1]
> > type SimpleRecord = (Integer, Integer, Integer)
> > type SimpleIndex = Integer
> > type SimpleDB = (Array SimpleIndex SimpleRecord, FilePath)
>
> > loadDB :: FilePath -> IO SimpleDB
> > loadDB f = do h <- openFile f ReadMode
> > s <- hGetContents h
> > hClose h
> > return $ r s
> > where r :: String -> SimpleDB
> > r = read
>
> > getRecord :: SimpleDB -> SimpleIndex -> SimpleRecord
> > getRecord (a, _) = (a !)
>
> > updateRecord :: SimpleDB -> SimpleIndex -> SimpleRecord -> SimpleDB
> > updateRecord (a, f) i r = (a//[(i,r)],f)
>
> > storeDB :: SimpleDB -> IO ()
> > storeDB sdb@(a,f) = do h <- openFile f WriteMode
> > hPutStr h (show sdb)
> > hClose h
>
> > sampleDB = (array (0,10) [(x,(x+1,x*2,42)) | x <- [0..10]],"output/
> 1.db.txt")
>
> [2] http://hsqldb.org/
>
> - Matt Munz
> mmm92 at pantheon.yale.edu
>
>
> _______________________________________________
> Haskell mailing list
> Haskell at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell
More information about the Haskell
mailing list