[Haskell-cafe] Polymorphic (typeclass) values in a list?

TJ tjay.dreaming at gmail.com
Fri Oct 19 11:57:45 EDT 2007

Henning Thielemann:
> > 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.

Yes, that's exactly the restriction I'm unhappy about.

> 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

But if I already have the types Point, Line, and Polygon, and I want
to create a "union type" Figure as above, then my code will look like

data Point = Point Something
data Line = Line Something
data Polygon = Polygon Something

data Figure
  = FPoint Point
  | FLine Line
  | FPolygon Polygon

aFigure = FPoint Point Something
aListOfFigures = [FPoint Point Something, FPolygon Polygon Something,
FLine Line Something]

> > 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

That's a nice page :) From a quick reading, the best I came up with was this:

data R = forall a. Renderable a => V a

instance Show R where
  render (R a) = render a

Which is precisely what I meant when I said that I'd still have to
wrap things up in a constructor. Is this hidden type variable thing
what "existential types" mean?

OT: forall just introduces a new type variable, right?



More information about the Haskell-Cafe mailing list