我有一个 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
用几个实例来包装您的 Board
和 BoardWithInfo
类型:
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/