vik santata
vik santata

Reputation: 3109

Haskell: when to use type class and when to use concrete type?

When declaring functions, we could either use type class or concrete type(Am I right?) So I can use "Num" as type indicator or "Int". I'm not sure if "Int" has any definition out of "Num"? Can I define my own concrete type that "inherit" from "Num"?

I ask this question from java/C# inheritance perspective, just begin with Haskell. Would you give some hints?

Upvotes: 1

Views: 831

Answers (1)

fjarri
fjarri

Reputation: 9726

From the OO perspective, a type class is something like an interface or a trait. In Haskell you generally use concrete types when you require a certain structure of the datatype (because you will unpack it), and a type class when you just want a certain behavior. For example, you can write

f :: Int -> Int -> Int
f x y = x + y

but you do not use the internal structure of Ints here; you just need something that supports addition, which is Num (note that it has a (+) in method list):

f :: Num a => a -> a -> a
f x y = x + y

And yes, of course, you can declare that your own class supports the Num interface. Look at the link above, there is a list of methods called "minimal complete definition". This is what other functions that use it will rely on. In a pinch, you may explicitly set some methods to undefined, but you'll get a runtime error if someone tries to call them:

data MyData = MyData Int Int

instance Num MyData where
    (MyData x1 y1) + (MyData x2 y2) = MyData (x1 + y1) (x2 + y2)
    (*) = undefined
    ...

See how you use your knowledge of MyData structure to abstract possible users of your class from it? If they want to add two values of this type together, they do not need to know how the data is arranged inside, they just need to know that it is an instance of Num.

Upvotes: 7

Related Questions