I\'m pretty new a Haskell programming. I\'m trying to deal with its classes, data, instances and newtype. Here is what I\'ve understood:
data NewData = Const
Another way to think about the Haskell data structure is this "discriminated union" construction in C:
typedef enum { constr1, constr2 } NewDataEnum;
typedef struct {
NewDataEnum _discriminator;
union {
struct { int a,b; } _ConStr1;
struct { float a,b; } _ConStr2;
} _union;
} NewData;
Note that in order to access any of the Int or Float values in the Haskell type you have to pattern match the constructor, and this corresponds to looking at the value of the _discriminator
field.
For example, this Haskell function:
foo :: NewData -> Bool
foo (ConStr1 a b) = a + b > 0
foo (ConStr2 a b) = a * b < 3
could be implemented as this C function:
int foo(NewData n) {
switch (n._discriminator) {
case constr1: return n._union._ConStr1.a + n._union._ConStr1.b > 0;
case constr2: return n._union._ConStr2.a * n._union._ConStr2.b < 3;
}
// will never get here
}
For completeness, here are the implementation of the constructor ConStr1
using the above C definitions:
NewData ConStr1(int a, int b) {
NewData r;
r._discriminator = constr1;
r._union._ConStr1.a = a;
r._union._ConStr1.b = b;
return r;
}
Java and C# don't have direct support for unions. In a C union all of the fields of the union are assigned the same offset within the containing structure and so the size of the union is the size of its largest member. I've seen C# code which doesn't worry about wasting space and simply uses a struct
for a union. Here is an MSDN article which discussed how to the get the overlapping effect that C-style unions have.
Algebraic data types are in many ways complementary to objects - things that are easy to do with one are difficult to do with the other - and so it is not surprising that they don't translate well to an OO implementation. Any discussion of the "Expression Problem" usually highlights the complementary nature of these two systems.
Objects, type classes and algrbraic data types may be thought as different ways to efficiently transfer control by means of a jump table, but the location of this table is different in each of these cases.
_vptr
)Finally, it should be emphasized that in Haskell you specify very few implementation details of algebraic data types (ADTs). The discriminated union construction is a useful way to think about ADTs in concrete terms, but Haskell compilers are not required to implement them in any specific way.