[Haskell-cafe] Data declaration vs type classes

Jonas Scholl anselm.scholl at tu-harburg.de
Fri Jan 8 10:56:43 UTC 2016

On 01/08/2016 11:38 AM, Imants Cekusins wrote:
>> How should one go about deciding to use data or class?
> class:
> class lets specify more than one method. when you define instance yet
> do not implement all methods, compiler warns.
> if you try to call class method without an instance for that type,
> compiler warns.
> pattern matching:
> compiler does not warn if methods do not match every constructor of
> the data type.

Well, there is -fwarn-incomplete-patterns, which should be included in
-Wall, which does exactly this.

> one way to decide if not sure, is to pick one way which seems easier
> to refactor. when more code is written, it usually becomes obvious if
> this approach does not fit. then refactor.

A few things to keep in mind: If you define a type class and instances
for Int and String, and later want to add another case for String, you
have to add a newtype, otherwise the compiler can not differentiate.
Additionally, adding a constructor with multiple fields gets complicated
if you choose the type class solution, here you have to add an instance
for a tuple.

Also you need FlexibleInstances as soon as you want an instance for
String or a Tuple more specific than (a, b) (or introduce newtypes).

You can also not process a Task if it is hidden in a class. For example,
how do you implement doOnlyShoppingTask? In the end you restrict
yourself with a type class about the things you can do with the data.

So when is this useful? I would argue, if you are writing a library and
want your users to be able to define their own tasks. Otherwise I think
abstracting a data type with a type class is not worth the hassle.

>> Which is more appropriate here?
> depends on the rest of the code. if this is it, then there is no real
> difference.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 473 bytes
Desc: OpenPGP digital signature
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20160108/d5b8e74a/attachment.sig>

More information about the Haskell-Cafe mailing list