[Haskell-beginners] Default values for Data Types?

Brandon S. Allbery KF8NH allbery at ece.cmu.edu
Wed Sep 24 00:25:41 EDT 2008

On 2008 Sep 22, at 15:38, Mike Sullivan wrote:
> I was wondering if there is syntactic sugar in Haskell for defining  
> a default value for fields in a data type. For instance, say I have  
> a type that is defined in record syntax:
> type CustomerID = Int
> type Address = Maybe String
> data Customer = Customer {
> customerID :: CustomerID
> , customerName :: String
> , customerAddress :: Address
> } deriving (Show)
> Is there any way to define default values for some (or all) fields  
> such that they may be omitted from a declaration, and still have it  
> generate a valid object?
> e.g.)
> a = Customer{customerID = 12, customerName="Bill"}
> -- I would like a{customerAddress} to default to Nothing (for  
> instance).
> It seems to me that this would be a nice feature to have, if it does  
> not exist. Am I missing something?

aCustomer = Customer { customerAddress = Nothing }
-- ...
a = aCustomer { customerID = 12, customerName = "Bill" }

This will net you a compile time warning about uninitialized fields in  
aCustomer, and if you fail to initialize a Customer properly it will  
produce a runtime error:

     *Main> customerName b
     "*** Exception: fooo.hs:6:12-49: Missing field in record  
construction Main.customerName

You will *not* get  a warning for missing values in variables  
initialized this way, only for the special initializer value.  I'm not  
sure if it's possible to make the type system handle this, but if it  
is then it'll probably be painful and ugly.  (Now watch someone post  
an elegant one-liner....)

brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university    KF8NH

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20080924/226bc439/attachment.htm

More information about the Beginners mailing list