34

Basic question: what design principles should one follow when choosing between using a class or using a record (with polymorphic fields) ?

First, we know that classes and records are essentially equivalent (since in Core, classes get desugared to dictionaries, which are just records). Nevertheless, there are differences: classes are passed implicitly, records must be explicit.

Looking a little deeper, classes are really useful when:

  1. we have many different representations of 'the same thing', and
  2. in actual usage, which representation is used can be inferred.

Classes are awkward when we have (up to parametric polymorphism) only one representation of our data, but we have multiple instances. This leads to the syntactic noise of having to use newtype to add extra tags (which exist only in our code, as we know such tags get erased at run time) if we don't want to turn on all sorts of troublesome extensions (i.e. overlapping and/or undecidable instances).

Of course, things get muddier: what if I want to have constraints on my types? Let's pick a real example:

class (Bounded i, Enum i) => Partition a i where
    index :: a -> i

I could just as easily have done

data Partition a i = Partition { index :: a -> i}

But now I've lost my constraints, and I will have to add them to specific functions instead.

Are there design guidelines that would help me out?

6
  • You can keep constraints in the record too: data Partition a i = Partition { index :: a -> i, iBounded :: Bounded i, iEnum :: Enum i }.
    – Rotsor
    Nov 12, 2011 at 19:34
  • @Rotsor - nice. I guess I can put in dummy values (ie undefined) too, as long as I can provide for witnesses of the constraints. I'll need to conduct some experiments with that, to see if coding in this way is 'comfortable'. Nov 12, 2011 at 19:40
  • 12
    For the constraints, use GADT syntax, data Partition x y where Partition :: (Bounded i, Enum i) => { index :: a -> i } :: Partition a i. Nov 12, 2011 at 20:40
  • 1
    For most usage I prefer not having the constraints carried around with the data type. I find I rarely actually need them. Of course YMMV. Also, have you considered the Implicit Parameters extension?
    – John L
    Nov 13, 2011 at 0:47
  • 1
    @JohnL: no, I had not. And I happen to not like that particular extension. But I agree that it is 'in scope', in the design space being discussed. Nov 13, 2011 at 2:55

3 Answers 3

7

I tend to see no issue with only requiring constraints on functions. The issue is, I suppose, that your data structure no longer models precisely what you intend it to. On the other hand, if you think of it as a data structure first and foremost, then that should matter less.

I feel like I don't necessarily still have a good grasp on the question, and this is about as vague as can be, but my rule of thumb tends to be that typeclasses are things that obey laws (or model meaning), and datatypes are things that encode a certain quantity of information.

When we want to layer behavior in complex ways, I've found that typeclasses start off enticingly, but can get painful quickly and switching to dictionary-passing makes things more straightforward. Which is to say that when we want implementations to be interoperable, then we should fall back to a uniform dictionary type.


This is take two, expanding a bit on a concrete example, but still just sort of spinning ideas...

Suppose we want to model probability distributions over the reals. Two natural representations come to mind.

A) Typeclass-driven

class PDist a where
        sample :: a -> Gen -> Double

B) Dictionary-driven

data PDist = PDist (Gen -> Double)

The former lets us do

data NormalDist = NormalDist Double Double -- mean, var
instance PDist NormalDist where...

data LognormalDist = LognormalDist Double Double
instance PDist LognormalDist where...

The latter lets us do

mkNormalDist :: Double -> Double -> PDist...
mkLognormalDist :: Double -> Double -> PDist...

In the former, we can write

data SumDist a b = SumDist a b
instance (PDist a, PDist b) => PDist (SumDist a b)...

in the latter we can simply write

sumDist :: PDist -> PDist -> PDist

So what are the tradeoffs? Typeclass-driven lets us specify what distributions we're given. The tradeoff is that we have to construct an algebra of distributions explicitly, including new types for their combinations. Data-driven doesn't let us restrict the distributions we're given (or even if they're well-formed) but in return we can do whatever the heck we want.

Furthermore we can write a parseDist :: String -> PDist relatively easily, but we have to go through some angst to do the equiv for the typeclass approach.

So this is, in a sense the typed/untyped static/dynamic tradeoff at another level. We can give it a twist though, and argue that the typeclass, along with associated algebraic laws, specifies the semantics of a probability distribution. And the PDist type can indeed be made an instance of the PDist typeclass. Meanwhile, we can resign ourselves to using the PDist type (rather than typeclass) nearly everywhere, while thinking of it as iso to the tower of instances and datatypes necessary to use the typeclass more "richly."

In fact, we can even define basic PDist function in terms of typeclass functions. i.e. mkNormalPDist m v = PDist (sample $ NormalDist m v) So there's lots of room in the design space to slide between the two representations as necessary...

6
  • You may be on to something here. Maybe if you illustrated your thinking with some examples which show good/bad uses of classes and records? Nov 14, 2011 at 18:24
  • "So there's lots of room in the design space to slide between the two representations as necessary" is pretty much the starting point for my questions! You do spell out some of the tradeoffs (on top of some I had mentioned). I am trying to get at design principles that would help guide the decision process in that design space. Maybe we can start with the obvious stuff: why is Monad best as a typeclass? And a Person (learnyouahaskell.com/making-our-own-types-and-typeclasses) is best as a record? Nov 14, 2011 at 23:25
  • @Jacques -- my argument is more that there's not an either/or choice, I think. The issue is more about dynamic vs. static behavior, with an attendant tradeoff in how much can be checked at compile-time. A data type seems appropriate when there is one way (upto iso) or one way at a time for an X to be a Y, while a record is more appropriate when there are (potentially infinitely) many ways to relate X and Y. This is a weird question for s/o in part because its somewhat subjective, and in part because I think your judgement is as good as or better than most on these topics to begin with.
    – sclv
    Nov 15, 2011 at 17:16
  • When you put it all together, I mean, data are functions, functions are data, classes are records, classes are control structures, functions are control structures, data is a control structure... I find it very hard to articulate the one right approach -- it becomes more a matter of circumstance and taste. Which, I suppose, is precisely the issue...
    – sclv
    Nov 15, 2011 at 17:24
  • And one more thought -- isn't the most general solution invariably tagless? :-)
    – sclv
    Nov 15, 2011 at 21:29
4

Note: I'm not sure that I understand the OP exactly. Suggestions/comments for improvement appreciated!


Background:

When I first learned about typeclasses in Haskell, the general rule-of-thumb I picked up was that, in comparison to Java-like languages:

  • typeclasses are similar to interfaces
  • data are similar to classes

Here's another SO question and answer that describe guidelines for using interfaces (also some drawbacks of interface over-use). My interpretation:

  • records/Java-classes are what something is
  • interfaces/typeclasses are roles that a concretion can fulfil
  • multiple, unrelated concretions can fulfil the same role

I bet you already know all this.


The guidelines I try to follow for my own code are:

  • typeclasses are for abstractions
  • records are for concretions

So in practice this means:

  • let the needs of the data determine the records
  • let the client code determine what the interfaces are -- clients should depend on abstractions, and thereby drive the creation and design of typeclasses

Example:

typeclass Show, with function show :: (Show s) => s -> String: for data that can be represented as a String.

  • clients just want to turn data into strings
  • clients don't care what the data (concretion) is -- only care that it can be represented as a string
  • role of implementing data: can be string-ified
  • this could not be achieved without a typeclass -- each datatype would require a conversion function with a different name, what a pain to deal with!
4
  • I hope to add more examples and refactor the answer soon -- I don't think I've made my point very well. Nov 13, 2011 at 16:22
  • thanks, this does seem to be 'going in the right direction'. Looking forward to the refactor + more examples. Nov 13, 2011 at 21:02
  • @JacquesCarette -- after re-reading your question, I think I may have answered the wrong question. Is your question asking specifically for the case when one datatype has multiple instances of a typeclass (for example, list + Applicative: also ZipList)? I thought it was more a general typeclass vs. data question. Oops!!!!! Nov 14, 2011 at 13:49
  • The question really is about the general case (i.e design guidelines), not the specific case of the example. Nov 14, 2011 at 18:22
1

Type-classes can sometimes provide additional type-safety (An example would be Ord with Data.Map.union). If you have similar circumstances where choosing type-classes may help your type-safety - then use type-classes.

I'll present a different example where I think type-classes would not provide additional safety:

class Drawing a where
    drawAsHtml :: a -> Html
    drawOpenGL :: a -> IO ()

exampleFunctionA :: Drawing a => a -> a -> Something
exampleFunctionB :: (Drawing a, Drawing b) => a -> b -> Something

There is nothing exampleFunctionA could do and exampleFunctionB could not do (I find it hard to explain why, insights are welcome).

In this case I see no benefit of using a type-class.

(Edited following feedback from Jacques and question from missingo)

6
  • 2
    While this is an interesting example, it really is not a "design guideline" that allows me to make a choice, is it? It shows that, in some cases (which you do not define), classes are better. This, I knew. I am looking for "design guidelines". Nov 12, 2011 at 22:23
  • 1
    What about when the functions tables are built at runtime? Would this be a caveat to your "try to always use Type Classes" suggestion?
    – hugomg
    Nov 12, 2011 at 22:27
  • 1
    (my first comment was about a version of the answer that has been edited to remove 'the example') Nov 12, 2011 at 22:45
  • @missingno: I revised my question and addressed your question with an example class where I see no benefit for type-class over a record.
    – yairchu
    Nov 12, 2011 at 22:48
  • 1
    @yairchu: I appreciate the attempt. Nov 13, 2011 at 2:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.