Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Algebraic data vs Tuple

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) = …
like image 815
mk12 Avatar asked May 17 '12 00:05

mk12


People also ask

What is algebraic data type in Haskell?

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)

Can lists in Haskell have different types?

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")] .

What is a data constructor Haskell?

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.

How do you define a new type in Haskell?

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.


1 Answers

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.

like image 61
Don Stewart Avatar answered Oct 17 '22 20:10

Don Stewart