Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Records with default values
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-03-23 (19:41)
From: Jeffrey Cook <jeffrey.j.cook@g...>
Subject: Records with default values
Is there an existing (or even possible to do with) camlp4 extension to
support default values in records?  I am constantly finding myself
doing the following:

type bob = {
    foo : string ;    <--- field for which no default value makes sense
    bar : int ;         <--- field(s) that have default values

let bob_default = { foo = ""; bar = 0; }

with usage:

let x = { bob_default with foo = "hello" }

so that I do not have to fill in the numerous fields that really
should default to some value.

Without using this solution, my code is often cluttered with many
doldrum default value declarations for record fields (worsened by
multiple sites that define the initial record values), obscuring what
the important assignments were.  Additionally, I often find that the
complex fields (of record types, for example) are the ones that don't
lend themselves to a default value whereas the simple types do.  This
leads to the use of options (discussed below) just to save from even
uglier default value declarations for fields that never use a default.

Using a default structure like above also does not let me harness the
type checking mechanisms to detect places in my code where a field
(that really shouldn't have a default value) wasn't defined as is
normally the case when constructing a record from scratch - especially
when fields are later added to the record.

Using 'options' for no-default-value fields doesn't seem to be a very
good solution, as there then need to be runtime deconstructors of the
options (and runtime checks or uncaught exceptions) if a field has a
None value that should have been set.  All that aside, it still
wouldn't identify where the record was incompletely 'created' using
the default record.

What I would like is the following:

type bob = {
    foo : string ;
    bar : int := 0 ;

let x = { foo = "hello" }

(and maybe even some kind of 'nodefaults' annotation when defining 'x'
if I want to make sure I've explicitly defined every field.)

So what advice / solutions do other people have / use?


Jeffrey Cook
Ph.D. Candidate, Electrical Engineering
University of Illinois at Urbana-Champaign