In C# I can declare the following
class A {
int Field;
}
class B : A {
int Field2;
}
static int f(A a) { return a.Field; }
static int f(B b) { return a.Field + b.Field2; }
static void Main(string[] args) {
A a = new A() { Field = 1 };
A b = new B() { Field = 1, Field = 2};
Console.WriteLine(f(a) + f(b));
}
In Haskell I would type out the above as
data A = A { field :: Int } | B { field :: Int, field2 :: Int }
f :: A -> Int
f (A a) = a
f (B a b) = a + b
main :: IO()
main = do putStrLn $ show (f(a) + f(b))
where a = A 1
b = B 1 2
What I don't like about the Haskell counterpart is that I have to repeat field
twice in the data definition of A
(this becomes more tiresome as the number of fields increases that are present in A
that need to be in B
). Is there a more concise way in Haskell to write B
as a subclass of A
(that is somewhat similar to the C# way)?