[Haskell-beginners] Record types with multiple constructors

Michael Snoyman michael at snoyman.com
Sun Dec 7 09:47:33 UTC 2014


Yes: it becomes really easy to write partial/broken programs, e.g.:

let myEmployee = RegularEmployee "Alice"
    ...
    supervisor = myEmployee { salesTarget = 5.4 }

If you want to have both multiple constructors *and* multiple fields per
constructor, I'd recommend one of the following:

1. Don't name the fields.
2. Use another type in between that has only one constructor, e.g. `data
Supervisor = Supervisor { name :: String, salesTarget :: Double }`. A great
example of this is the Node datatype[1] from xml-types.

[1]
http://www.stackage.org/haddock/2014-11-27-ghc78-exc-1/xml-types-0.3.4/Data-XML-Types.html#t:Node

On Sun Dec 07 2014 at 11:37:16 AM Derek McLoughlin <
derek.mcloughlin at gmail.com> wrote:

> Hi,
>
> Record types usually have a single constructor. I've even seen blog
> posts that suggest that they must have a single constructor. However,
> multiple constructors are allowed:
>
> data Employee = RegularEmployee {
>                                   name :: String
>                              } |
>                              Supervisor {
>                                   name :: String,
>                                   salesTarget :: Double
>                              }
>                              Manager {
>                                   name :: String,
>                                   salesTarget :: Double
>                                   budget :: Double
>                              }
>
> I don't see this used much in Haskell code - either in explanatory
> books/tutorials or in code I've examined on GitHub. Are there
> drawbacks to using multiple constructors in this way?
>
> Derek.
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20141207/030625db/attachment.html>


More information about the Beginners mailing list