[Haskell-cafe] Re: Default (or empty) values

Max Vasin max.vasin at gmail.com
Wed Jan 17 10:57:03 EST 2007


>>>>> "Henning" == Henning Thielemann <lemming at henning-thielemann.de> writes:

Henning> On Wed, 17 Jan 2007, Max Vasin wrote:

> Hello all!
>> 
>> Let
>> 
>> > data Book = Book { > authors :: [String], > title :: String,
>> > editor :: Maybe String, > edition :: Maybe String, > volume
>> :: Maybe (Int, Int), -- e.g. volume 1 of 3 > publisher ::
>> String, > year :: Int, > pages :: Int
>> > } 
>> 
>> and
>> 
>> > convertBook :: Map String String -- a map from field names to
>> values (string representation) > -> Maybe Book
>> 
>> convertBook takes info about book from some external source
>> (e.g. a BibTeX database) and returns Just book value or Nothing
>> (if convertion failed). Fields of the Book datatype which are
>> not (Maybe a) are required to be present.
>> 
>> convertBook looks like
>> 
>> > convertBook = (rq "title" (\b v -> b { title = v }) <.> > rq
>> "publisher" (\b v -> b { publisher = v }) <.> > ... ) (Just $
>> Book [] "" Nothing Nothing Nothing "" 0 0)
>> 
>> I don't like the `(Just $ Book [] "" Nothing Nothing Nothing ""
>> 0 0)' part, I would prefer instead someting like `empty ::
>> Book'. So I define
>> 
>> > class Empty e where > empty :: e
>> 
>> But still I have to emplement instances by hand. There are a
>> number of approaches to automatically derive instances (TH,
>> generic classes in GHC, drift). What would you recommend using
>> in this case?  Or may be it would be better to drop out Empty
>> and use something else?

Henning> Using a record with named fields is good style, as you
Henning> pointed out later.  Stick to it!  Why do you need a type
Henning> class? What about simply

Henning> empty :: Book empty = Book [] "" Nothing Nothing Nothing
Henning> "" 0 0

Well the type class is not necessary, a TH function generating
an empty value for given datatype. OTOH convertBook can be
rewritten (using type class) as:

> convertBook = (rq "title" (\b v -> b { title = v }) <.> 
>                rq "publisher" (\b v -> b { publisher = v }) <.>
>                ... )

and it will be used like 'convertBook empty'. I like this way more
since convertBook looks more declarative.

Henning> For updates empty { title = "new title" } is perfectly
Henning> ok.

Henning> You can also let undefined fields undefined. In

Henning> Book {}

This will be enough if there were no optional fields.

-- 
WBR,
Max Vasin.



More information about the Haskell-Cafe mailing list