[Haskell-cafe] Subtype polymorphism in Haskell

aditya siram aditya.siram at gmail.com
Mon Jul 5 09:33:40 EDT 2010


Does this work for you?

data A a = A (Int,Int)
data B
data C

class A_Class a where
  do_x :: a -> Int
instance A_Class (A B) where
  do_x (A (a,b)) = a + b
instance A_Class (A C) where
  do_x (A (a,b)) = a - b

-- > do_x ((A (1,2)) :: A B)
-- 3
-- > do_x ((A (1,2)) :: A C)
-- -1

-deech

On Mon, Jul 5, 2010 at 9:22 AM, Simon Courtenage <courtenage at gmail.com> 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
> courtenage at gmail.com
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>


More information about the Haskell-Cafe mailing list