I found answers explaining difference between newtype
and data
in Haskell. But if I have the following type synonym:
type Point = (Int,Int)
Would that be more efficient rather to use:
data Point = Pt (Int,Int) ?
Type and data type refer to exactly the same concept. The Haskell keywords type and data are different, though: data allows you to introduce a new algebraic data type, while type just makes a type synonym. See the Haskell wiki for details.
In Haskell, types are how you describe the data your program will work with.
As data type already represents the type of value that can be stored so values can directly be assigned to the data type variables. On other hand in case of data structure the data is assigned to using some set of algorithms and operations like push, pop and so on.
Haskell is a non-strict language, and most implementations use a strategy called laziness to run your program.
Using type
will be more efficient, as it incurs one less indirection than the data
version.
Note that both are more inefficient than:
data Point = Point {-# UNPACK #-}!Int {-# UNPACK #-}!Int
as you can see from this earlier question on data representations.
Yes.
The Pt construction adds one word of overhead (in GHC) and the field (i.e. the pair) is stored as a pointer to a pair, adding one additional word, for a total of two words overhead (and an extra indirection to get to the values).
I recommend that you either use the type synonym or, better yet, define
data Point = Pt {-# UNPACK #-} !Int {-# UNPACK #-} !Int
This requires 4 words less than
type Point = (Int, Int)
and uses one less level of indirections (pointers).
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