How to organize Haskell modules with instances: stick to data type vs type class?

Viewed 1807

The general question is which module structure is more convenient when adding instances for existing objects? Which pros and cons there are?

Let's say I want to add NFData instance for Seq type. I can place it in:

  • Data.Sequence.Extra (as the same thing is done in the vty package)
  • Data.Sequence.Instances.NFData (more precise)
  • Control.DeepSeq.Instances
  • Control.DeepSeq.Instances.Sequence

It's the case when I don't own neither the type class nor the data type. The other common situation is when I own a type type class and want to add instances for data type(s) from some "heavy" package from Hackage, like OpenGL. Let's say the type class I designed is very light and has no direct relation to OpenGL. I don't want my type class depend on "heavy" package, so I want to place OpenGL instances in a separate module (it's my intuitive feeling, if you have other opinion, let's discuss it). So, what this module should be:

  • MyClass.Instances.OpenGL
  • Graphics.Rendering.OpenGL.Extra (together with instances for other classes)
  • Graphics.Rendering.OpenGL.Instances.MyClass

What is more flexible solution? At some point OpenGL can be replaced with other library, or MyClass can be replaced too. Are there any subtle nuances?

Also, which scheme is better if choose MyClass.Instances variant:

  • MyClass.Class module for the class itself and basic instances and MyClass module reexports it (and maybe MyClass.Instances)
  • MyClass module for the class and basic instances, and MyClass.All reexports everything
  • MyClass module for the class and basic instances and no module for reexporting.
1 Answers
Related