[Haskell-cafe] Subtype polymorphism in Haskell
Tillmann Rendel
rendel at Mathematik.Uni-Marburg.de
Mon Jul 5 10:19:36 EDT 2010
Simon Courtenage wrote:
> 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.
They probably do not contribute at all.
> 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) { ...}
> };
I guess B and C are subclasses of A?
If you do not need complicated subtyping schemes, you could consider on
of the following two options: You could emphasize the structure of the
class hierarchy, or you could emphasize the object abstraction.
The structure of the class hierarchy could be represented by an
algebraic data type
data A = B | C
with the do_x function implementing by pattern matching on an A value
do_x :: A -> Int -> Int -> Int
do_x B = ...
do_x C = ...
If your classes have fields, they could be added as fields to the data
constructors B and C.
Alternatively, the object abstraction could be represented by encoding
objects as records of first-class functions.
data A = A {
do_x :: Int -> Int -> Int
}
b = A {do_x = \x y -> ...}
c = A {do_x = \x y -> ...}
If your classes have fields, they could be added as arguments to
constructor functions b and c.
Tillmann
More information about the Haskell-Cafe
mailing list