Haskell - add class?

Consider the following example:

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

First, I would like to overload the + operator to add Vector . If I wanted to overload the equality operator ( == ), I would write it like this:

 instance Eq Vector where ...blahblahblah 

But I canโ€™t find out if there is an Add typeclass to make Vector behave like a type with an add operation. I canโ€™t even find the complete list of Haskell classes, I only know a few from different tutorials. Is there such a list?

Also, can I overload the + operator to add Vector to the Dot (this seems pretty logical, right?).

+4
source share
4 answers

The + operator in Prelude is defined by the Num type class. However, as the name implies, this not only defines the addition, but also many other numerical operations (in particular, other arithmetic operators, as well as the possibility of using numerical literals), so this is not suitable for your use.

It is not possible to overload only + for your type if you do not want to hide the Prelude + operator (which would mean that you need to create your own additional instance for Integer, Double, etc., if you still want to use + by numbers).

+7
source

An easy way to find out information about which class (if any) belongs to the GHCi function:

 Prelude> :i (+) class (Eq a, Show a) => Num a where (+) :: a -> a -> a ... -- Defined in GHC.Num infixl 6 + 
+13
source

You can write instance Num Vector to overload + to add vectors (and other operators that make sense).

 instance Num Vector where (Vector x1 y1) + (Vector x2 y2) = Vector (x1 + x2) (y1 + y2) -- and so on 

However, note that + is of type Num a => a -> a -> a , i.e. both operands and the result must all be of the same type. This means that you cannot have a Dot plus a Vector be Dot .

While you can hide Num from Prelude and specify your own + , this is likely to cause confusion and make it harder to use your code along with regular arithmetic.

I suggest you define your own operator to add a vector point, e.g.

 (Dot xy) `offsetBy` (Vector dx dy) = Dot (x + dx) (y + dy) 

or some option using characters if you prefer something shorter.

+5
source

I sometimes see people defining their own statements that look like those from Prelude. Even ++ probably uses this symbol because they need something that conveys the idea of โ€‹โ€‹โ€œaddingโ€ two lists together, but the list did not make sense to be an instance of Num . So you can use <+> or |+| or something like that.

+4
source

All Articles