Looking at the following code:
data Point = Point Float Float deriving (Show)
data Shape = Circle Point Float | Rectangle Point Point deriving (Show)
which is from the book Learn you a Haskell for Great Good, which accompanies this code example with the following text:
Notice that when defining a point, we used the same name for the data type and the value constructor. This has no special meaning, although it's common to use the same name as the type if there's only one value constructor.
Now my assumption is that data Point = ...
is the data type, and ... = Point Float...
is the value constructor.
My question is: Is it common to use the same name for the data type and value constructor in Haskell?
Type constructor The data type is polymorphic (and a is a type variable that is to be substituted by a specific type). So when used, the values will have types like Tree Int or Tree (Tree Boolean) .
A value constructor is the only part you would call a "constructor" in other (object oriented) languages, because you need it in order to build values for that type.
Haskell has three basic ways to declare a new type: The data declaration, which defines new data types. The type declaration for type synonyms, that is, alternative names for existing types. The newtype declaration, which defines new data types equivalent to existing ones.
A data constructor is a "function" that takes 0 or more values and gives you back a new value.
From my limited experience: Yes. It makes sense, too. Why would you call Point
differently here? It perfectly describes the data type and is also clear to use for pattern matching like this
myFunc :: Point -> Bool
myFunc (Point 0 0) = True
myFunc _ = False
It is unambiguous since you can only put the data type in the type signature of the function.
This is not a direct answer, but a tip for people with the same question.
Syntax highlighting may help with the distinction between the two. For example a screenshot of some of the code mentioned before, from Visual Studio Code with a Haskell Syntax Highlighting extension (with customized color coding):
Not everybody seems to agree with the accepted answer, by the way. See for example this short post, as well as this r/haskell discussion about it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With