[Haskell-beginners] Re: how to define a user datatype consisting of instances of String?

Daniel Fischer daniel.is.fischer at web.de
Thu Oct 23 06:24:00 EDT 2008


Am Donnerstag, 23. Oktober 2008 11:48 schrieb Benjamin L.Russell:
> On Thu, 23 Oct 2008 18:39:52 +0900, Benjamin L. Russell
>
> <DekuDekuplex at Yahoo.com> wrote:
> >instance Show Wine where
> >    show (Red Merlot) = "Merlot"
> >    show (Red Syrah) = "Syrah"
> >    show (Red Port) = "Port"
> >    show (White SauvignonBlanc) = "Sauvignon Blanc"
> >    show (White Riesling) = "Riesling"
> >    show (White PinotNoir) = "Pinot Noir"
> >
> >instance Show Red where
> >    show Merlot = "Merlot"
> >    show Syrah = "Syrah"
> >    show Port = "Port"
> >
> >instance Show White where
> >    show SauvignonBlanc = "Sauvignon Blanc"
> >    show Riesling = "Riesling"
> >    show PinotNoir = "Pinot Noir"
>
> The only remaining issue is whether there is a way to define the type
> constructor for Wine without pre-defining parts that are later defined
> in the type constructors for Red and White.

You could make it

type Grape = String
type Colour = String
data Wine = Wine { grape :: Grape, colour :: Colour }

but you'd face the possibility of (Wine "" "petillant") - bad.
To have only real wines, you have to do it more or less as it is or leave out 
the Red and White types and make Wine an enumeration without colour tag.
>
> In the above code, for example,
>
> >instance Show Wine where
> >    show (Red Merlot) = "Merlot"
>
> essentially pre-defines the following definition later given in the
>
> type constructor for Red:
> >instance Show Red where
> >    show Merlot = "Merlot"

with the below Show instance of Wine,

instance Show Red where
	show = show . Red

instance Show White where
	show = show . White

would save a bit of typing.
But the other way round,
instance Show Wine where
	show (Red w) = show w
	show (White w) = show w
seems cleaner.
>
> This seems redundant.
>
> Since the type definition for Wine is
>
> data Wine = Red Red | White White
>
> the type constructors for Red and White both require an argument, so
>
> show (Red Merlot) = ...
>
> seems reasonable.
>
> This would seem to imply that if I need to reduce redundancy, I should
> probably rewrite the RHS of the above line.
>
> Is there a way to refer to the type constructors for Red and White in
> the type constructor for Wine?

I don't understand what you mean, certainly not
data Wine a = W a
and
W Merlot :: Wine Red
?
>
> -- Benjamin L. Russell
>
Cheers,
Daniel


More information about the Beginners mailing list