1
votes

I am going through Hudak's "Gentle introduction to Haskell". As stated in my earlier questions, I have a little experience with C and C++. So when I came across the term "Constructors" in the introduction to type constructors and data constructors I can't help but wonder if any similarities are there with C++ constructors or is it completely analogous with the later.

So, the first example that Hudak provides is the following:

data Color  = Red|Green|Blue 

So from the first example I got to know that the RHS is the data constructor. However, here I wasn't clear about type constructors.

In the next example:

data Point a = Pt a a

It has been clearly stated that Point is the data constructor and Pt is the type constructor. So what exactly does a constructor do? Is it a function call as it is in case of C++?

How exactly are the work of point and pt differentiated? what is "pt" doing?

2
You've got it the wrong way round: Point is the type constructor and Pt is the data constructor.melpomene

2 Answers

1
votes

I think you're getting a bit bogged down in terminology. I'd probably say "Point is a higher-kinded type" instead. That just means that it forms a new type given another type. Usually we just refer to Pt as a constructor. Here's an example:

data Point a = Pt a a

samplePoint :: Point Int
samplePoint = Pt 1 2
1
votes

A constructor can indeed be used to, well, construct a value (or type, respectively), like a C++ class constructor can:

Prelude> data Point a = Pt a a
Prelude> :type Pt
Pt :: a -> a -> Point a
Prelude> :kind Point
Point :: * -> *

This corresponds, roughly, to

template <typename A>
struct Point {
  A x, y;
  Point(A x, A y): x(x), y(y) {}
};

...or, to get the same name,

template <typename A>
Point Pt(A x, A y) { return Point(x,y); }

But that's not all, a value constructor can also be used to deconstruct a value:

centerDist :: Floating a => Point a -> a
centerDist (Pt x y) = sqrt $ x^2 + y^2

There's nothing really analogous in C++ because that doesn't have pattern matching.