Search code examples
arrayshaskellbinarybytestring

Datatype to ByteString


I have a newtype I'd like to save in a file, something like this:

type Index = (Int, Int)

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

So basically an Array. But maybe I want to add some other data one day like this:

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

And so on. I just want to know, are there any convenient, optimised functions to do this, Array to ByteString and combined data - and the other way around. Or how to write my own, if there are not.


Solution

  • You could derive a Show instance and save it as such, or check the binary module from hackage. IIRC it has instance for Arrays. You need to create your instance for your newtype, but as it's just a wrapper, it's a no-brainer. The binary module has excellent documentation with lots of examples.