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
andRead
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-
read
able) text is nowhere near as efficient as a tag-based binary format. For this, you can use thebinary
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 usingShow
andRead
! (Just use the functionsencodeFile
anddecodeFile
(OrFail
) from theData.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. :)