[Haskell-beginners] Haskell-style types in C or C++

Ertugrul Soeylemez es at ertes.de
Sun Jul 31 21:58:06 CEST 2011


Christopher Howard <christopher.howard at frigidcode.com> wrote:

> One of the things that I love about Haskell is the syntax for creating
> user defined types. E.g.:
>
> Data QueryResult = NoResult | DatabaseError String | Results [String]
>
> I can prototype an entire program around these self-made types and it
> is a lot of fun. Out of intellect curiosity, though: what would be the
> equivalent construction in C or C++? (Say, for the type defined
> above).

I think, the closest and cleanest translation is a set of four classes,
one QueryResult superclass with subclasses NoResult, DatabaseError and
Results.  This also gives you something resembling Haskell's value
constructors, although not for free.  Finally it helps with separation
of concerns, when you write accessor functions.  You don't get pattern
matching, but you can get combinators like 'maybe' for Maybe or 'either'
for Either.

Unions work, too, but they are not nearly as clean.  In general, avoid
unions in C++, even though they seem to be a natural way to express
ADTs.  They really are not.  Class hierarchies are the way to go.


Greets,
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/





More information about the Beginners mailing list