[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:40:29 EDT 2008


Am Donnerstag, 23. Oktober 2008 12:19 schrieb Benjamin L.Russell:
> >
> >You have basically two choices, you can say everybody knows which colour
> > the wines have and use
> >
> >instance Show Wine where
> >	show (Red w) = show w
> >	show (White w) = show w
> >
> >or include the colour in the rendered String, for example via deriving
> > Show, or by declaring your own instance (if you want White PinotNoir
> > rendered as "White (Pinot Noir)", you would have to do that or write a
> > more complicated Show instance for White).
> >If you want to parse values of type Wine in the future, it will be
> > slightly easier with the dataconstructors included.
>
> So perhaps I should rewrite the type definitions for Red and White as
> follows?
>
> data Red = Syrah | Merlot | Port deriving (Eq, Show)
> data White = SauvignonBlanc | Riesling | PinotNoir deriving (Eq, Show)

That would be the easiest, but of course having the two Whites displayed with 
a space is aesthetically superior.

>
> Alternatively (adapted from an example provided by Dirk Thierbach in
> the thread "seeking helpful links," dated "Tue, 21 Oct 2008 16:33:41
> -0700 (PDT)," on comp.lang.haskell), perhaps the following?
>
>   type Entree = String
>   type SideDish = String
>   type Wine = String
>
>   wine :: Entree -> SideDish -> Wine
>   wine "Kobe Beef"    "Buttered Potatoes"       = "Syrah"
>   wine "Kobe Beef"    "Brie Cheese"  = "Syrah"
>   wine "Kobe Beef"    "Greek Salad"             = "Sauvignon Blanc"
>   wine "Lemon Chicken" "Buttered Potatoes"       = "Merlot"
>   wine "Lemon Chicken" "Brie Cheese"  = "Sauvignon Blanc"
>   wine "Lemon Chicken" "Greek Salad"             = "Merlot"
>   wine "Steamed Salmon"    "Buttered Potatoes"       = "Sauvignon
> Blanc"
>   wine "Steamed Salmon"    "Brie Cheese"  = "Port"
>   wine "Steamed Salmon"    "Greek Salad"             = "Port"
>
>   wines :: [Entree] -> [SideDish] -> [(Entree, SideDish, Wine)]
>   wines entrees sideDishes = [(e, s, wine e s) | e <- entrees, s <-
> sideDishes]

The downside of that is that a typo in the entrees or sideDishes will explode 
with a pattern match failure. Otherwise it's concise and clean.
>
> >>[...]
> >
> >Bon Appetit,
> >Daniel
> >
> >P.S.: Could I have a Syrah with my beef and potatoes?
>
> Certainly; here is your Syrah with your beef and potatoes.  Bon
> appetit ;-) :
>

Merci, c'était délicieux.
>
> -- Benjamin L. Russell
>



More information about the Beginners mailing list