Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One data versus 2 datas in Haskell

Tags:

haskell

Is there any big difference:

data Point = IntPoint Int Int
           | FloatPoint Float Float

over

data IntPoint = IntPoint Int Int
data FloatPoint = FloatPoint Float Float
like image 853
Alan Coromano Avatar asked Dec 15 '22 07:12

Alan Coromano


1 Answers

It depends on what you want to do with it.

data Point = IntPoint Int Int
           | FloatPoint Float Float

Here the same type Point has two data constructors IntPoint and FloatPoint. For example, you can write a single function that takes a value of type Point and do something with it depending if it is an IntPoint or a FloatPoint. Here is an example function which checks if the line joining origin and the point forms 45 degree with x-axis.

isDiagonal :: Point -> Bool
isDiagonal (IntPoint i j) = i == j
isDiagonal (FloatPoint i j) = i == j

On the other hand,

data IntPoint = IntPoint Int Int
data FloatPoint = FloatPoint Float Float

Here IntPoint and FloatPoint are separate types with IntPoint and FloatPoint as data constructors respectively. Now you have to write separate functions having different names for each type.

isDiagonalInt :: IntPoint -> Bool
isDiagonalInt (IntPoint i j) = i == j

isDiagonalFloat :: FloatPoint -> Bool
isDiagonalFloat (FloatPoint i j) = i == j

There are ways to write a polymorphic function for the above case using typeclasses but thats another story.

like image 87
Satvik Avatar answered Dec 30 '22 04:12

Satvik