Search code examples
haskellderived-types

Why explicit derivation of Show/Read in Haskell?


We can't do read someValue :: someDataType or show someValue for every type because deriving (Show, Read) has to be written in the data declarations. Is there a case, other than mistake, where we don't want our type to be serializable? Why is Show separated from Read? Is there a case, other than mistake, we only want to show some data and not read it? If not, why not have a single data type Serializable?

Just now, I'm using the Key datatype of the Gloss library which derives Show and not Read, which I don't understand. It's a shame because I wanted to put the configuration of the controls in a file and then read it, so the player can change the controls and have his own configuration. I had to do wrappers for Key, SpecialKey and MouseButton, which is not a big deal but is useless.

data Key' = Char' Char | SpecialKey' SpecialKey | MouseButton' MouseButton
    deriving (Eq, Ord, Show, Read)
convertKey x = case x of
    Char' c -> Char c
    SpecialKey' sk -> SpecialKey sk
    MouseButton' mb -> MouseButton mb

Solution

  • Why is Show separate from Read

    I don't know why this was originally, but feel it should persist because some (very few) types can be shown, or have a placeholder string shown, but not read back in. Functions are the typical example.

    Another way to think about it: It's very easy to place things in separate classes but very hard to deal with too many functions in one class that doesn't always make sense in the same contexts. Many people feel the Num class is a prime example of this issue.

    How Can I read Key and other types not in Read

    Step one: send in a patch adding Read to the set of derived instances. Step two: make a work around by using standalone deriving:

    {-# LANGUAGE StandaloneDeriving #-}
    deriving instance Show Key
    

    Step three: Use CPP to make your code work with either version of the codebase, be it the Gloss library with a Read instances that Ben will someday release or the version without.

    Why isn't there a Serializable class?

    For starters, there is a Serialize class. Also, text is a horrible way to serialize things. Perhaps you'd want a lazier serialize class in which case you should see the Binary class. If you're concerned about performance then you might like blaze-builder, though I've honestly never used it.