Difference between revisions of "Name clashes in record fields"

From HaskellWiki
Jump to navigation Jump to search
(prime link fix)
(link to latest released user guide, not master)
(One intermediate revision by the same user not shown)
Line 32: Line 32:
 
=== Using [[language extension]] ===
 
=== Using [[language extension]] ===
   
<code>[https://downloads.haskell.org/~ghc/master/users-guide/glasgow_exts.html#duplicate-record-fields DuplicateRecordFields]</code> extension (GHC 8.0.1+) allow definition of record types with identically-named fields.
+
<code>[https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#duplicate-record-fields DuplicateRecordFields]</code> extension (GHC 8.0.1+) allow definition of record types with identically-named fields.
   
 
== See also ==
 
== See also ==

Revision as of 19:41, 4 April 2019

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 function name somehow into that.

Using language extension

DuplicateRecordFields extension (GHC 8.0.1+) allow definition of record types with identically-named fields.

See also