haskell Data.Binary示例

时间:2012-08-10 16:37:04

标签: haskell

我正在尝试序列化一个联系人类型,但我坚持定义put和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

2 个答案:

答案 0 :(得分:4)

是的,您很难定义putget。这会回答你的问题吗?

type Name = String
type Address = String

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

由于已有实例:

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

你应该能够轻松解除潜在的看跌期权并获得惯例:

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

因此,当您放置联系人时,您只需告诉它放置字符串对列表。如果要反序列化联系人,只需获取基础列表并使用Contacts构造函数。

答案 1 :(得分:4)

添加更多简单示例,以防止其他新手像我一样痛苦:)

{-# 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)