[Haskell-cafe] Default (or empty) values

Henning Thielemann lemming at henning-thielemann.de
Wed Jan 17 09:37:14 EST 2007


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?

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

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

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

You can also let undefined fields undefined. In

Book {}

all fields are undefined.


More information about the Haskell-Cafe mailing list