My thanks to everyone who replied with their helpful comments.  You are
right that I forgot to add the public inheritance on the C++ classes (that's
what happens when you write code in an email without passing it through a
compiler first).

I like the idea below, which is easy to understand.  It seems to me, though,
that there's a lot more to the use of typeclasses than is covered in some of
the haskell textbooks, and if anyone knows of a good in-depth treatment of
this, I would be grateful for a pointer.

Thanks again to everyone who responded,

Simon

On Mon, Jul 5, 2010 at 2:28 PM, Miguel Mitrofanov <miguelim...@yandex.ru>wrote:

> My guess is that it's
> class B : public A
> and
> class C : public A
>
> In this case it seems perfect to use type classes:
>
> class A t where do_x :: t -> Integer -> Integer -> Integer
> data B = ...
> instance A B where do_x b x y = ...
> data C = ...
> instance A C where do_x c x y = ...
>
> If you want some general "A" object, you can use existentials (or, better
> yet, GADTs):
>
> data A_general = forall t. A t => A_general t
>
> or
>
> data A_GADT where A_GADT :: A t => t -> A_GADT
>
> so that
>
> int foo (A v) {... v.do_x(1,2)...}
>
> becomes
>
> foo :: A_GADT -> Integer
> foo (A_GADT v) = ... do_x v 1 2 ...
>
> Simon Courtenage wrote:
>
>> Hi,
>>
>> I am porting a C++ program to Haskell.  My current task is to take a class
>> hierarchy and produce something equivalent in Haskell, but I don't seem to
>> be able to get a grip on how type classes and instances contribute to the
>> solution.  Can anyone enlighten me?
>>
>> Roughly, the class hierarchy in C++ is of the form
>>
>> class A {
>> public:
>>   virtual int do_x(int,int) = 0;
>> };
>>
>> class B {
>> public:
>>   int do_x(int x,int y) { ...}
>> };
>>
>> class C {
>> public:
>>   int do_x(int x,int y) { ...}
>> };
>>
>> Any help would be greatly appreciated.
>>
>> Thanks
>>
>> Simon
>> courten...@gmail.com <mailto:courten...@gmail.com>
>>
>>
>>
>> ------------------------------------------------------------------------
>>
>> _______________________________________________
>> Haskell-Cafe mailing list
>> Haskell-Cafe@haskell.org
>> http://www.haskell.org/mailman/listinfo/haskell-cafe
>>
>


-- 
------------------------------------------------------------------------
Simon Courtenage                     | simoncourtenage.wordpress.com
Twitter: simoncourtenage         | Skype: simon99ctg
Facebook: Simon Courtenage   | IM: simon2...@hotmail.com
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to