Difference between revisions of "Name clashes in record fields"
Jump to navigation
Jump to search
(initialized from a Haskell-Cafe thread) |
(→Using language extension: fix link) |
||
(5 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
== Question == |
== Question == |
||
+ | <code> error| Multiple declarations of ‘xxx’ </code> |
||
I like to define: |
I like to define: |
||
Line 6: | Line 7: | ||
data Dog = Dog {name :: String} |
data Dog = Dog {name :: String} |
||
</haskell> |
</haskell> |
||
+ | |||
− | Why is this forbidden? |
+ | Why is this forbidden? |
I like to define: |
I like to define: |
||
Line 28: | Line 30: | ||
* write a typeclass with a <hask>name</hask> function and fit the non-accessor function <hask>name</hask> somehow into that. |
* write a typeclass with a <hask>name</hask> function and fit the non-accessor function <hask>name</hask> somehow into that. |
||
+ | === Using [[language extension]] === |
||
+ | |||
+ | {{GHCUsersGuide|exts/duplicate_record_fields||a DuplicateRecordFields section}}. The extension (GHC 8.0.1+) allow definition of record types with identically-named fields. |
||
== See also == |
== See also == |
||
− | * [ |
+ | * [https://gitlab.haskell.org/haskell/prime/-/wikis/type-directed-name-resolution ''Type directed name resolution'' in the Haskell Prime Wiki] |
* Haskell-Cafe on [http://www.haskell.org/pipermail/haskell-cafe/2010-December/087859.html Record types and unique names] |
* Haskell-Cafe on [http://www.haskell.org/pipermail/haskell-cafe/2010-December/087859.html Record types and unique names] |
||
Latest revision as of 20:08, 23 July 2021
Question
error| Multiple declarations of ‘xxx’
I like to define:
data Human = Human {name :: String}
data Dog = Dog {name :: String}
Why is this forbidden?
I like to define:
data Human = Human {name :: String}
name :: Cat -> String
name = ...
Why is this forbidden, too?
Answer
The record field accessors name
are just functions
that retrieve the field's value from a particular record.
They are in the global scope together with top-level functions
and thus cannot have the same name.
For resolving this you may:
- rename the accessor or the top-level function
- put the data declaration or the top-level function in another module and import qualified
- write a typeclass with a
name
function and fit the non-accessor functionname
somehow into that.
Using language extension
The GHC Users Guide has a DuplicateRecordFields section.. The extension (GHC 8.0.1+) allow definition of record types with identically-named fields.