Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - add typeclass?

Consider the following example:

data Dot = Dot Double Double
data Vector = Vector Double Double

First, i would like to overload + operator for Vector addition. If i wanted to overload equality(==) operator, i would write it like:

instance Eq Vector where ...blahblahblah

But I can't find if there is Add typeclass to make Vector behave like a type with addition operation. I can't even find a complete list of Haskell typeclasses, i know only few from different tutorials. Does such a list exist?

Also, can I overload + operator for adding Vector to Dot(it seems rather logical, doesn't it?).

like image 957
karlicoss Avatar asked Jul 30 '11 12:07

karlicoss


2 Answers

An easy way to discover information about which typeclass (if any) a function belongs to is to use GHCi:

Prelude> :i (+)
class (Eq a, Show a) => Num a where
  (+) :: a -> a -> a
  ...
        -- Defined in GHC.Num
infixl 6 +
like image 168
Boris Avatar answered Oct 30 '22 16:10

Boris


The operator + in Prelude is defined by the typeclass Num. However as the name suggests, this not only defines addition, but also a lots of other numeric operations (in particular the other arithmetic operators as well as the ability to use numeric literals), so this doesn't fit your use case.

There is no way to overload just + for your type, unless you want to hide Prelude's + operator (which would mean you have to create your own Addable instance for Integer, Double etc. if you still want to be able to use + on numbers).

like image 40
sepp2k Avatar answered Oct 30 '22 16:10

sepp2k