Multiple newtype constructors [GHC-05380]
A newtype can only have a single constructor. If you want multiple
constructors, you should use data
instead of newtype
.
The reason that you need exactly one constructor is that newtype
constructors
are removed at runtime.
For example, if you define newtype Age = Age Int
, the bits in memory that represent
an Age
are identical to those that would represent the Int
in the constructor.
The Age
and Int
types are distinguished only at compile time.
If types defined with newtype
could have multiple constructors, there would be no way to distinguish them during execution.
Examples
More than 1 constructor for a newtype
Error Message
Main.hs:1:1: error: [GHC-05380]
A newtype must have exactly one constructor,
but ‘Direction’ has two
In the newtype declaration for ‘Direction’
|
1 | newtype Direction = Up | Down
|
Explanation
A newtype
constructor can only have a single constructor.
It is not allowed to have multiple constructors when defining a newtype
.
More-than-1-constructor.hs
newtype Direction = Up | Down
data Direction = Up | Down
Zero constructors for a newtype
Error Message
Main.hs:1:1: error: [GHC-05380]
A newtype must have exactly one constructor, but ‘Void’ has none
In the newtype declaration for ‘Void’
|
1 | newtype Void
|
Explanation
A newtype
definition is required to have exactly one constructor, so constructorless newtype
s are not allowed.
Datatypes defined using data
are allowed to be constructorless,
so this problem can be fixed either by adding a constructor to the newtype
or by changing the newtype
keyword to a data
keyword.
Zero-constructors.hs
newtype Void
data Void