2

次のnewtypeようなファイルに保存したいものがあります。

type Index = (Int, Int)

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

つまり、基本的にはArray。しかし、多分私はこのような他のデータをいつか追加したいと思います:

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

等々。私はただ知りたいのですが、これを行うための便利で最適化された関数、ArrayデータByteStringの結合、およびその逆はありますか?または、ない場合は、自分で書く方法。

4

2 に答える 2

3

とタイプ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
于 2011-04-13T14:30:35.987 に答える
2

Showインスタンスを派生させて保存するか、ハッキングからバイナリモジュールを確認することができます。IIRCには配列のインスタンスがあります。newtypeのインスタンスを作成する必要がありますが、これは単なるラッパーであるため、簡単です。バイナリモジュールには、多くの例を含む優れたドキュメントがあります。

于 2011-04-13T13:52:49.083 に答える