In addition to the familiar
data keyword, Haskell provides us with another
way to create a new type, using the
-- file: ch06/Newtype.hs data DataInt = D Int deriving (Eq, Ord, Show) newtype NewtypeInt = N Int deriving (Eq, Ord, Show)
The purpose of a
newtype declaration is to
rename an existing type, giving it a distinct identity. As we can see,
it is similar in appearance to a type declared using the
Although their names are similar, the
keywords have different purposes. The
type keyword gives us another way of
referring to a type, like a nickname for a friend. We and the compiler
know that [Char] and String names refer to
the same type.
In contrast, the
keyword exists to hide the nature of a type.
Consider a UniqueID type:
-- file: ch06/Newtype.hs newtype UniqueID = UniqueID Int deriving (Eq)
The compiler treats UniqueID as a different type from Int. As a user of a UniqueID, we know only that we have a unique identifier; we cannot see that it is implemented as an Int.
When we declare a
we must choose which of the underlying type’s typeclass instances we
want to expose. Here, we’ve elected to make NewtypeInt
provide Int’s instances for Eq,
Ord, and Show. As a result, we can compare and
print values of type NewtypeInt:
N 1 < N 2True
Since we are not exposing Int’s Num or Integral instances, values of type NewtypeInt are not numbers. For instance, we can’t ...