[Add info on serialization to ch5 John Goerzen **20070619075910] { hunk ./en/ch05-typeclasses.xml 410 + + + Serialization with Read and Show + + Often times, you may have a data structure in memory that you need to + store on disk for later retrieval or send across the network. The + process of converting data in memory to a flat series of bits for + storage is called serialization. + + + It turns out that &read; and &show; make excellent tools for + serialization. &show; produces output that is both human-readable and + machine-readable. It also mostly matches Haskell syntax. + + + Let's try it out in &ghci;: + + &serialization.ghci:ex1; + + First, we assign d1 to be a list. Next, we print + out the result of show d1 so we can see what it + generates. Then, we write the result of show d1 + to a file named /tmp/test. + + + Let's try reading it back. + + &serialization.ghci:ex2; + + First, we ask Haskell to read the file back.As you will see + in FIXME: insert ref, Haskell doesn't actually + read the entire file at this point. But for the purposes of this + example, we can ignore that distinction. Then, + we try to assign the result of read input to + d2. That generates an error. The reason is that + the interpreter doesn't know what type d2 is meant + to be, so it doesn't know how to parse the input. If we give it an + explicit cast, it works, and we can verify that the two sets of data + are equal. + + + Since so many different types are instances of &Read; and &Show; by + default (and others can be made instances easily; see ), you can use it for + some really complex data structures. Here are a few examples of + slightly more complex data structures: + + &serialization.ghci:ex3; + addfile ./examples/ch05/serialization.ghci hunk ./examples/ch05/serialization.ghci 1 +--# ex1 +let d1 = [Just 5, Nothing, Nothing, Just 8, Just 9]::[Maybe Int] +putStrLn (show d1) +writeFile "/tmp/test" (show d1) +--# ex2 +input <- readFile "/tmp/test" +let d2 = read input +let d2 = (read input)::[Maybe Int] +print d1 +print d2 +d1 == d2 +--# ex3 +putStrLn $ show [("hi", 1), ("there", 3)] +putStrLn $ show [[1, 2, 3], [], [4, 0, 1], [], [503]] +putStrLn $ show [Left 5, Right "three", Left 0, Right "nine"] +putStrLn $ show [Left 0, Right [1, 2, 3], Left 5, Right []] }