Good day. I'm new to Haskell. One thing is not clear for me concerning declaring and instantiating some custom classes.
There is a standard class
Integral
in haskell. According to the hackage,Integral
declares the mandatory methodquot :: a -> a -> a
. So it means that every instance of that class should have this method implementation, right?We can declare some function, using Integral as an argument, like:
proba :: (Integral a) => a -> a -> a
proba x y = x `quot` y
So far so good
- Now lets declare our own class Proba:
class Proba a where
proba :: a -> a -> a
I can implement an Int or Integer (or other data type) instance like this:
instance Proba Integer where
proba x y = x `quot` y
instance Proba Int where
proba x y = x `quot` y
But I don't want to. I want one instance for every Integral. But when I try to do it, I get an error:
instance (Integral a) => Proba a where
proba x y = x `quot` y
Illegal instance declaration for `Proba a'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use FlexibleInstances if you want to disable this.)
In the instance declaration for `Proba a'
Ok, it seems that it asks me for distinct type variables instead of classes. But why?! Why isn't it enough for it just to have an Integral
here? Since quot
is declared for every Integral
, this instance should be valid for every Integral
, shoudn't it?
Maybe there is a way to achieve the same effect?
Use FlexibleInstances if you want to disable this.
Have you tried doing that? – Bartek Banachewicz