arrays - 数据类型到 ByteString

标签 arrays haskell binary bytestring

我有一个 newtype 我想保存在一个文件中,如下所示:

type Index = (Int, Int)

newtype Board a = Board { unboard :: Array Index a }

所以基本上是一个数组。但也许有一天我想添加一些其他数据,如下所示:

data BoardWithInfo a = BWI {
    bwiBoard :: Board a,
    bwiRef :: String,
    bwiStart :: Index
}

等等。我只是想知道,是否有任何方便的、优化的函数来执行此操作,从 Array 到 ByteString 以及组合数据,以及反之亦然。或者如果没有的话如何编写我自己的。

最佳答案

您需要使用Data.Binary用几个实例来包装您的 BoardBoardWithInfo 类型:

import Control.Monad
import Data.Array
import Data.Binary

type Index = (Int, Int)

newtype Board a = Board { unboard :: Array Index a }
                deriving (Eq, Show)

instance (Binary a) => Binary (Board a) where
  get = liftM Board get
  put b = put (unboard b)

data BoardWithInfo a = BWI { bwiBoard :: Board a
                           , bwiRef :: String
                           , bwiStart :: Index }
                     deriving (Eq, Show)

instance (Binary a) => Binary (BoardWithInfo a) where
  get = liftM3 BWI get get get
  put b = do
    put (bwiBoard b)
    put (bwiRef b)
    put (bwiStart b)

testBoard :: Board Int    
testBoard = Board $ listArray ((1,1),(10,10)) [1..100]

testBWI :: BoardWithInfo Int
testBWI = BWI testBoard "test" (1,1)

-- returns True since the data survives encoding/decoding!
testBinaryRoundtrip = testBWI == testBWI'
  where
    testBWI' = decode $ encode testBWI

关于arrays - 数据类型到 ByteString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5650052/

相关文章:

java - Java 中的列表数组

c - 如何在没有无限循环的情况下获得 N 个唯一的随机量?

java数组: How to deal with an array condition in java

Haskell 相当于 Rust 的 GAT?

haskell - 类型类、关联族 -> 容器、​​键和元素 : Who is who?

c++ - 使用boost序列化读取批量大小的二进制文件

python - 为什么修改字典中的键也会修改分配给它们的数组? (Python)

math - Haskell 中四舍五入到特定位数

python - 如何将内容与作为二进制和其他形式内容容器的文件分离

binary - Maxmind 的二进制 DAT 是如何工作的?