2

我正在尝试序列化 Contacts 类型,但我一直在定义 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
4

2 回答 2

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构造函数。

于 2012-08-10T16:42:00.373 回答
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)
于 2012-08-10T23:51:00.803 回答