Haskell data serialization of some data implementing a common type class

Posted by Evan on Stack Overflow See other posts from Stack Overflow or by Evan
Published on 2012-10-14T01:53:04Z Indexed on 2012/10/14 3:37 UTC
Read the original article Hit count: 234

Filed under:
|
|

Let's start with the following

data A = A String deriving Show
data B = B String deriving Show

class X a where
    spooge :: a -> Q

[ Some implementations of X for A and B ]

Now let's say we have custom implementations of show and read, named show' and read' respectively which utilize Show as a serialization mechanism. I want show' and read' to have types

show' :: X a => a -> String
read' :: X a => String -> a

So I can do things like

f :: String -> [Q]
f d = map (\x -> spooge $ read' x) d

Where data could have been

[show' (A "foo"), show' (B "bar")]

In summary, I wanna serialize stuff of various types which share a common typeclass so I can call their separate implementations on the deserialized stuff automatically.

Now, I realize you could write some template haskell which would generate a wrapper type, like

data XWrap = AWrap A | BWrap B deriving (Show)

and serialize the wrapped type which would guarantee that the type info would be stored with it, and that we'd be able to get ourselves back at least an XWrap... but is there a better way using haskell ninja-ery?

EDIT

Okay I need to be more application specific. This is an API. Users will define their As, and Bs and fs as they see fit. I don't ever want them hacking through the rest of the code updating their XWraps, or switches or anything. The most i'm willing to compromise is one list somewhere of all the A, B, etc. in some format. Why?

Here's the application. A is "Download a file from an FTP server." B is "convert from flac to mp3". A contains username, password, port, etc. information. B contains file path information. A and B are Xs, and Xs shall be called "Tickets." Q is IO (). Spooge is runTicket. I want to read the tickets off into their relevant data types and then write generic code that will runTicket on the stuff read' from the stuff on disk. At some point I have to jam type information into the serialized data.

© Stack Overflow or respective owner

Related posts about haskell

Related posts about serialization