2011-04-13 64 views
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 
} 

依此類推。我只想知道,是否有任何方便的優化功能來執行此操作,ArrayByteString以及組合數據 - 反之亦然。或者如果沒有,我該怎麼寫自己的。

回答

2

你可以派生一個Show實例並保存它,或者從hackage中檢查二進制模塊。 IIRC它有Arrays的實例。你需要爲你的newtype創建你的實例,但因爲它只是一個包裝器,所以這是一個簡單的方法。二進制模塊有很多很好的例子。

+0

+1; 'Data.Binary'非常適合使用,特別是如果您只關心在磁盤上放置位而不是匹配特定格式。 – acfoltzer 2011-04-13 14:01:56

+0

感謝您使用'Data.Binary'提示,這是一個很好的幫手。 – Lanbo 2011-04-13 14:29:44

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 
相關問題