Deserializing to different types at runtime in haskell

Viewed 243

Background

I'm working with the Aeson library to store and retrieve values from a file. I am using Typeable (and TypeReps) to tag the data so I have a pretty good idea that it will parse correctly.

I have a Class wherein each member of the class has a function that takes a time (Integer) and updates itself ie:

class Update a where
  update :: Integer -> a -> a

All the values stored in the file are Instances of the Update class.

Question I would like to iterate through the file updateing each value and write a new file. I would like to have the program determine at runtime what the data type of the chunk of data is, use fromJSON to create value of that type, run update on it, and write it back. The type checker thinks this is a terrible idea because it cannot statically type check the fromJSON call at compile time and therefore cannot get the right entry from the Update class dictionary.

Is there a way to use Typeable (or Data) to get the type checker to do the right thing? Is there a better alternative?


My only thought on working around this is to create a union data type of all updateable types, and then use a case statement to parse the tag and choose the correct constructor. I'm not real happy with this solution because I cannot add new types to the update class without also touching this union type.

2 Answers
Related