Default values in records

From HaskellWiki
Revision as of 23:07, 28 April 2009 by Lemming (talk | contribs) (taken from a post to Haskell-Cafe)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Question

Is there a way to declare default value of some fields when defining a new record type?

Anwser

You cannot associate default values with a type, but you can define as many record values as you like and use them as basis for updating elements.

data Foo = Foo { bar :: Int, baz :: Int, quux :: Int }

fooDefault = Foo { bar = 1, baz = 2, quux = 3 }

newRecord = fooDefault { quux = 42 }

If you only want some of the fields to be defaulted, you can make them undefined in the default record. Unfortunately this won't be statically checked by the compiler.

Source