[Haskell-beginners] How to best handle classes of types, interactions and listing of different types?

Daniel Bergey bergey at alum.mit.edu
Tue May 24 20:15:13 UTC 2016

On 2016-05-23 at 12:06, Silent Leaf <silent.leaf0 at gmail.com> wrote:
> Say there's a class, many types that can instantiate it. Then, i in fact need to be able
> to concatenate (mappend would be ideal!), make lists of values of different types, all
> instantiating the class.

In most cases, when Haskell beginners want to make a list that contains
several types from a single type class, there's a better way to organize
the code.  If you post your code, I'll try to suggest a specific

In general, try to find a simple data type that captures the same fields
& functions as an unknown type that is part of the type class.  Here's
an example.

We have a type class for vectors in a metric space, and instances for
2D, 3D, etc.

> class Metric v where
>     length :: v -> Double
>     (*^) :: Double -> v -> v

This class has the law:  s * length v == length (s *^ v)

Instead of a heterogeneous list [ V2 1 2, V3 3 4 5, V4 6 7 8 9], we make
a list that just has the length of each vector, and lets us multiply
those lengths by a scalar.  In this case, we don't even need to write a
new data type, the type is simply Double.  We can write:

> [ length (V2 1 2), length (V3 3 4 5), length (V4 6 7 8 9) ]

And (*) gives us what Metric does with (*^).  Of course, with your
class, it's probably not so obvious how to transform the class this way.

It's certainly possible to make a record with functions as members,
moving in the object-oriented direction.  Existential types (with a
class constraint inside the data constructor) are even more rarely used.


More information about the Beginners mailing list