[Haskell-cafe] Polymorphic (typeclass) values in a list?
Henning Thielemann
lemming at henning-thielemann.de
Fri Oct 19 11:11:37 EDT 2007
On Fri, 19 Oct 2007, TJ wrote:
> Why is it illegal to store values of differing types, but which
> instance the same class, into a list? e.g.
>
> a = [ 1, 2.0 ] :: Num a => [a]
>
> After all, sometimes all you need to know about a list is that all the
> elements support a common set of operations. If I'm implementing a 3d
> renderer for example, I'd like to have
>
> class Renderable a where
> render :: a -> RasterImage
>
> scene :: Renderable a => [a]
This signature is valid, but it means that all list elements must be of
the same Renderable type.
> Instead of hardcoding a bunch of types as being Renderable, as in
>
> data Renderable
> = Point Something
> | Line Something
> | Polygon Something
>
> scene :: [Renderable]
You could let the user plug together the alternatives for Renderable. That
is, declare the class Renderable and let the user define and instantiate
data Figure
= Point Something
| Line Something
| Polygon Something
or
data Shape
= Point Something
| Line Something
| Polygon Something
| Spline Something
or whatever he needs. That's a Haskell 98 solution.
> Or maybe
>
> data Point = Point Something
> data Line = Line Something
> data Polygon = Polygon Something
>
> scene :: { points :: [Point], lines :: [Line], polygons :: [Polygons] }
>
>
> Is there a way of achieving what I want to do? Existentials maybe? I'm
> still learning the basic stuff and don't grok existentials at all, but
> I even if I use those, I'll still have to wrap things up in a
> constructor, won't I?
I assume, that you could use
http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#universal-quantification
More information about the Haskell-Cafe
mailing list