gpt4 book ai didi

haskell Data.Binary 示例

转载 作者:行者123 更新时间:2023-12-02 11:14:55 25 4
gpt4 key购买 nike

我正在尝试序列化联系人类型,但我无法定义 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

最佳答案

是的,您在定义 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

您应该能够轻松地提升底层的 put 和 get 例程:

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

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

关于haskell Data.Binary 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11905826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com