Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the naming convention for typeclasses in Scala?

In Java world, the naming conventions for interfaces are pretty much well established. For instance, when you say certain class implements the interface Comparable, you can say that it's objects are comparable. However the naming conventions for typeclasses are not so well established. For example, Int has a Numeric implicit available, so you can say "Int is a Numeric type". But then there is typeclass Ordering. I fail to see why this name was chosen. "Int is an Ordering type" doesn't make any sense. Perhaps it is supposed to be read as "Int type has an Ordering". Then there are Equal and Show in Scalaz. I totally have no idea why these names were chosen (apart from that they are so in Haskell.) I tried looking at Haskell, the mother language of typeclasses, for a good naming convention but found that there doesn't really exist any. Haskell guys don't really seem to care about names (That's what I gathered from the mailing list discussions). But coming from Java world, I do care about names. I am not quite able to get accustomed to "types say it all" paradigm.

The question is: What naming conventions do you follow, if at all you do, for naming the typeclasses?

like image 820
Jim Gordowsky Avatar asked Aug 16 '11 19:08

Jim Gordowsky


1 Answers

Actually, things are mostly straightforward in Haskell: Type classes are typically named based on what the operations represent, not what the type parameter represents.

For example:

  • Read, Show: Classes of types for which standard string serialization/deserialization functions are defined.
  • Eq, Ord: Classes of types on which equality and ordering relations, respectively, are defined.
  • Enum: The class of types defining a "successor" operation, i.e., whose values can be enumerated.
  • Monoid, Functor, Monad: Classes of types which define the operations associated with the similarly-named mathematical structures.

Some examples aren't so good: For instance, Num is a class of types on which an ad-hoc collection of vaguely-arithmetic-oriented operations are defined, but there's no reason that an instance of Num must actually be a number in any conventional sense. This could perhaps be handwaved as "types supporting numeric operations", pretending that "numeric" actually means anything in that phrase.

In short, Numeric is probably a bad example to imitate, and if a type class has only one function (possibly with multiple variants on it), it's almost always safe to name the class after that function, as with show vs. Show.

But really, the main thing is to think in terms of the functions on the type class, not the type parameter. Think verbs, not nouns. Nouns are dumb inert things anyway, so thinking in terms of actions and operations is likely to lead to better program design.

like image 184
C. A. McCann Avatar answered Oct 11 '22 19:10

C. A. McCann