Question

AFAIK there is no way to do heterogeneous arrays in Haskell or extend data type. However it seems it could be achieved easily by using nested pair (like CONS are).

For example

data Point2D a = Point2D a a
data Point3D a = Point3D a a a

Could be written using nested pair like this;

type Point2D = (a, (a, ())
type Point3D = (a, (a, (a, ()))

That way accessors can be common for Point2D and Point3D

x = fst
y = fst.snd
z = fst.snd.snd

This technique can also be used to extend record like this

type Person = (String, ())
name = fst
type User = (String, (String, ())
email = fst.snd

etc ...

Is it a good idea and if so , why is there no built-in support for such thing in Haskell ? Is it what GADT is about ?

Was it helpful?

Solution

It can be a good idea, if that's what you need.

GADTs are not directly to do with this idea (if you want to know more about GADTs, probably better to google GADTs and read some of the links, and/or ask a separate Stackoverflow question).

There's no built in support for the same reason there's no built in support for graphics, matrix operations, or most other things; there's no need for support to be built in, because it can be added perfectly well by libraries, such as the HList package (indeed, even most of the functionality that is "built in" to Haskell is actually merely implemented in libraries; just libraries that happen to be always distributed with Haskell).

HList has fancy types for representing "heterogenous lists" and convenient functions for performing operations on them, and also uses these to develop "extensible records". HLists basically are equivalent to what you could do by developing your nested tuple idea further, so your basic idea is good enough that someone's already thought of it. :)

OTHER TIPS

Here is a way to have arbitrarily nested pairs:

data Y f = In (f (Y f))
data P a = Pair Int a | STOP
type PY = Y P

a, b :: PY
a = In (Pair 23 (In (Pair 24 (In STOP))))
b = In (Pair 23 (In (Pair 24 (In (Pair 25 (In STOP))))))    
c = [a,b]   -- a and b have same type
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top