Gert Cuykens
Gert Cuykens

Reputation: 7155

haskell Data.Binary example

I am trying to serialize a Contacts type but I am stuck at defining put and get?

import Control.Monad
import Data.Binary

type Name = String
type Address = String

data Contacts = Contacts [(Name, Address)] deriving (Show)
instance Binary Contacts where
    put (Contacts [(n,a)]) = do ...
    get = do ...

main :: IO ()
main = do
    let c = Contacts [("gert","home")]
    let e = encode c
    let d = decode e
    print d

Upvotes: 2

Views: 1790

Answers (2)

Gert Cuykens
Gert Cuykens

Reputation: 7155

Adding more simple examples to prevent other noobs from suffering like me :)

{-# LANGUAGE RecordWildCards #-}   
import Data.Binary

type Name = String
type Address = String
type Phone = String

data Contacts = Contacts [(Name, Address)] deriving (Show)
instance Binary Contacts where
    put (Contacts set) = put set
    get = fmap Contacts get

data Contact = Contact { name :: Name, address :: Address, phone :: Phone } deriving (Show)
instance Binary Contact where
    put Contact{..} = do put name; put address; put phone
    get = do name <- get; address <- get; phone <- get; return Contact{..}

main :: IO ()
main = do
    let c = Contacts [("gert","home"),("gert2","home2")]
    let e = encode c
    print e
    let d = decode e
    print (d:: Contacts)

    let c' = Contact{name="gert",address="home",phone="test"}
    let e' = encode c'
    print e'
    let d' = decode e'
    print (d':: Contact)

Upvotes: 4

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

Yes, you are stuck defining put and get. Does that answer your question?

type Name = String
type Address = String

data Contacts = Contacts [(Name, Address)] deriving (Show)
instance Binary Contacts
    put (Contacts [(n,a)]) = do ...
    get = do ...

Since there are already instances:

instance (Binary a) => Binary [a]
instance (Binary a, Binary b) => Binary (a,b)
instance Binary Char

You should just be able to trivially lift the underlying put and get routines:

instance Binary Contacts where
    put (Contacts set) = put set
    get = fmap Contacts get

So when you put contacts you just tell it to put the list of pairs of strings. When you want to deserialize the contacts you just get the underlying list and use the Contacts constructor.

Upvotes: 4

Related Questions