Haskell Data Structures – Is It Safe to Save and Retrieve Using Show and Read

data structureshaskell

Say I have the following types:

type EndsTup = (Int,Int)
    -- (0-based index from start or end, Frequency)
type FreqTup = (Char, [EndsTup], [EndsTup])
    -- (Character, Freqs from start, Freqs from end)
type FreqData = [FreqTup]
    -- 1 entry in the list for each letter

Which I'm using to store data regarding the frequency of a character's position in a word. If I want to then save this to file, is it safe (as in guaranteed not to corrupt if it's written without error) to convert the structure to a string using show, and then read it using something like:

readData <- readFile filePath
let reconstructed = read readData :: FreqData

I'm just asking because that seems "too easy". Is this how it's typically done?

Best Answer

It's perfectly safe to do it this way, especially since, as Doval pointed out, all the instances of Show and Read that you're using are in the standard library, and are thus guaranteed to cooperate with each other without any difficulty.

However, it's not the generally recommended way to do it, simply because saving to human-readable (and Haskell-readable) text is nowhere near as efficient as a tag-based binary format. For this, you can use the binary package, which already includes instances for all of the datatypes that you're using in the question.

More to the point, though, using the binary package to serialize to and deserialize from disk is even easier then using Show and Read! (Just use the functions encodeFile and decodeFile(OrFail) from the Data.Binary module.) In general, you will have to get used to things in Haskell being much simpler, at least in the common cases, then they typically are in most imperative languages. :)

Related Topic