data Ray = Ray Vector Vector
or
type Ray = (Vector, Vector)
Which is preferred in idiomatic haskell? Why should I use one over the other?
I don't care about performance.
It seems to make little difference with functions, e.g.:
trace :: Ray -> …
trace (Ray x d) = …
-- OR
trace (x, d) = …
This is a type where we specify the shape of each of the elements. Wikipedia has a thorough discussion. "Algebraic" refers to the property that an Algebraic Data Type is created by "algebraic" operations. The "algebra" here is "sums" and "products": "sum" is alternation ( A | B , meaning A or B but not both)
One is of type (String,Int) , whereas the other is (Int,String) . This has implications for building up lists of tuples. We could very well have lists like [("a",1),("b",9),("c",9)] , but Haskell cannot have a list like [("a",1),(2,"b"),(9,"c")] .
Data constructors are first class values in Haskell and actually have a type. For instance, the type of the Left constructor of the Either data type is: Left :: a -> Either a b. As first class values, they may be passed to functions, held in a list, be data elements of other algebraic data types and so forth.
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.
The data
version is preferred as it more clearly indicates the intent of the programmer — by creating a new type, you are pointing out to all that this is not merely a tuple, but a meaningful semantic entity, a Ray
.
That then makes it possible to lean on the type system further, with custom instances for Ray
, and optimizations not possible in tuples.
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