Send Beginners mailing list submissions to
[email protected]
To subscribe or unsubscribe via the World Wide Web, visit
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
or, via email, send a message with subject or body 'help' to
[email protected]
You can reach the person managing the list at
[email protected]
When replying, please edit your Subject line so it is more specific
than "Re: Contents of Beginners digest..."
Today's Topics:
1. Re: How to best handle classes of types, interactions and
listing of different types? (Daniel Bergey)
----------------------------------------------------------------------
Message: 1
Date: Tue, 24 May 2016 16:15:13 -0400
From: Daniel Bergey <[email protected]>
To: Silent Leaf <[email protected]>, The Haskell-Beginners
Mailing List - Discussion of primarily beginner-level topics related
to Haskell <[email protected]>
Subject: Re: [Haskell-beginners] How to best handle classes of types,
interactions and listing of different types?
Message-ID:
<87r3crxlf2.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me>
Content-Type: text/plain
On 2016-05-23 at 12:06, Silent Leaf <[email protected]> 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
solution.
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.
cheers,
bergey
------------------------------
Subject: Digest Footer
_______________________________________________
Beginners mailing list
[email protected]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
------------------------------
End of Beginners Digest, Vol 95, Issue 30
*****************************************