Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`deriving (Data)` vs `deriving (Generic)`

Tags:

haskell

ghc

What's the difference between these two in GHC. They seem similar in intended purpose but deriving (Data) has been around for a while yet deriving (Generic) has only been added to GHC recently.

Is deriving (Generic) basically an "upgrade" to deriving (Data) or do the two classes have different purposes?

like image 846
Clinton Avatar asked Sep 29 '14 03:09

Clinton


1 Answers

I almost hesitate to answer this question, because I only marginally understand it myself, but I did spend a couple of days looking at this myself about a year ago, and this is my current understanding....

Both classes are used for introspection.... Using them, you can get access to the Haskell code parsetrees (of the Haskell program itself).

Philosophically, the way that they do this differs, however.

  1. deriving (Data) creates data objects, which represent the parsed tree of objects that can be manipulated at runtime.

  2. deriving (Generic) creates new Types corresponding to each parsetree, which often can be manipulated at compile time (leaving less work to be done at runtime).

From my limited usage, "deriving (Data)" was much more straightforward to use, but of course wasn't as sleek at runtime (....for me this was negligable).

Although "deriving (Generic)" was theoretically faster, it was trickier to program, and involved creating classes that could manipulate groups of Types (ie- related parsetrees). It also may push you into using cutting edge GHC extensions.

My opinion- "deriving (Generic)" is the "right" way to do things, but would take longer to master.

Template Haskell is another way to access Haskell parsetrees, although it works 100% at compiletime, and has tools to let you create and insert parse tree data into the code (ie- code that generates code, like a Lisp macro).

Again, let me stress that this is all based on a couple of days of research, so if I have mangled this too badly, someone let me know (I myself would like to firm up my understanding).

like image 138
jamshidh Avatar answered Nov 15 '22 08:11

jamshidh