Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it common to use the same name for the data type and value constructor in Haskell?

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?

like image 243
hawkeye Avatar asked Jun 20 '16 08:06

hawkeye


People also ask

What is the datatype of a constructor?

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) .

What is a value constructor?

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.

How are datatype in Haskell defined and created?

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.

Is a constructor a function in Haskell?

A data constructor is a "function" that takes 0 or more values and gives you back a new value.


2 Answers

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.

like image 102
user3637541 Avatar answered Sep 19 '22 16:09

user3637541


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):

Haskell syntax highlighting

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.

like image 37
Reinier Torenbeek Avatar answered Sep 22 '22 16:09

Reinier Torenbeek