[Haskell-cafe] Newbie Question on type constructors
Jon Fairbairn
Jon.Fairbairn at cl.cam.ac.uk
Mon Nov 1 17:40:26 EST 2004
On 2004-11-02 at 00:11+0100 Benjamin Franksen wrote:
> On Monday 01 November 2004 22:34, I wrote:
> > data Shape = Circle Double | Square Double
> >
> > is a convenience that declares three new names (Shape,
> > Circle and Square), but five entities.
> >
> > There's Shape: a type, Circle, Square:: Double -> Shape:
> > constructor functions, and Circle, Square:: Shape -> (Double
> > -> t) -> t -> t: destructor functions.
>
> Interesting point of view! But... could you explain the
> types of the destructors? And how one would use them to
> deconstruct a Shape? Because, hmmm, isn't it rather *one*
> destructor with type
>
> destructShape :: Shape -> (Double -> t) -> (Double -> t) -> t
There could be, but that wouldn't suit my argument ;-)
> where the second and third arguments explain what to do
> with a Circle resp. a Square? So that
>
> case s of
> Circle r -> f r
> Square l -> g l
>
> is another way to write
>
> destructShape s g f
They amount to the same thing:
if Circle.destruct:: Shape -> (Double -> t) -> t -> t and
similarly Square.destruct, we'd just have to write the case
as
Circle.destruct s f (Square.destruct s g (error "impossible"))
ie the .destructs take a Shape, a function to apply if it
matches and a value to return if it doesn't.
Apart from matching up with the names there's not much to
choose between one destructor and many, except possibly when
one considers something like:
case e of
Square s -> ...
_ -> ...
particularly if the type has more than two constructors.
Jón
--
Jón Fairbairn Jon.Fairbairn at cl.cam.ac.uk
More information about the Haskell-Cafe
mailing list