One of the data compared to two data in Haskell

Is there a big difference:

data Point = IntPoint Int Int | FloatPoint Float Float 

above

 data IntPoint = IntPoint Int Int data FloatPoint = FloatPoint Float Float 
+4
source share
1 answer

It depends on what you want to do with it.

 data Point = IntPoint Int Int | FloatPoint Float Float 

Here, the same type of Point has two IntPoint and FloatPoint data constructors. For example, you can write one function that takes a value of type Point and do something with it, depending on whether it is IntPoint or FloatPoint . Here is an example function that checks to see if the line connecting the beginning and the point matches the 45-degree axis.

 isDiagonal :: Point -> Bool isDiagonal (IntPoint ij) = i == j isDiagonal (FloatPoint ij) = 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 need to write separate functions having different names for each type.

 isDiagonalInt :: IntPoint -> Bool isDiagonalInt (IntPoint ij) = i == j isDiagonalFloat :: FloatPoint -> Bool isDiagonalFloat (FloatPoint ij) = i == j 

There are ways to write a polymorphic function for the above case using type classes, but that's another story.

+12
source

Source: https://habr.com/ru/post/1498789/


All Articles