Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP style inheritance in Haskell

Tags:

c#

oop

haskell

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)?

like image 518
GEL Avatar asked Jul 15 '10 18:07

GEL


People also ask

Can you do OOP in Haskell?

Haskell isn't an object-oriented language. All of the functionality built here from scratch already exists in a much more powerful form, using Haskell's type system.

What is a Typeclass in Haskell?

Type Classes are a language mechanism in Haskell designed to support general overloading in a principled way. They address each of the concerns raised above. They provide concise types to describe overloaded functions, so there is no expo- nential blow-up in the number of versions of an overloaded function.

What does () mean in Haskell?

() is very often used as the result of something that has no interesting result. For example, an IO action that is supposed to perform some I/O and terminate without producing a result will typically have type IO () .

What is EQ Haskell?

The Eq class defines equality ( == ) and inequality ( /= ). All the basic datatypes exported by the Prelude are instances of Eq , and Eq may be derived for any datatype whose constituents are also instances of Eq . The Haskell Report defines no laws for Eq .


1 Answers

If A has a lot of fields, one design that might make sense is to have two different datatypes for A and B, where a B contains an A, and then use a typeclass to define f. Like so:

data A = A {field1 :: Int, field2 :: Int, ..., field9999 :: Int}
data B = B {a :: A, field10000 :: Int}

class ABC a where
    f :: a -> Int

instance ABC A where
    f a = field1 a + field101 a

instance ABC B where
    f b = f (a b) + field10000 b
like image 89
sepp2k Avatar answered Sep 19 '22 13:09

sepp2k