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

はい、 と の定義に行き詰まっていputますget。それはあなたの質問に答えていますか?

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

根底にある put と get ルーチンを自明に持ち上げることができるはずです。

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 に答える