I would like to define a function in a typeclass that outputs a result of an arbitrary Num type in Haskell. To illustrate this, I will use the below example:
class Exclass c where
exFunc :: (Num a) => c -> a
For a simple newtype shown below:
newtype Extype a = Extype a
I would like to write an instance of it under Exclass when the encapsulated value is of typeclass Num:
instance (Num b) => Exclass (Extype b) where
exFunc (Extype x) = x
However, the compiler compains that:
• Couldn't match expected type ‘a’ with actual type ‘b’
‘a’ is a rigid type variable bound by
the type signature for:
exFunc :: forall a. Num a => Extype b -> a
at C:\Users\ha942\OneDrive\Documents\Haskell\Qaskell\src\Example.hs:9:5-10
‘b’ is a rigid type variable bound by
the instance declaration
at C:\Users\ha942\OneDrive\Documents\Haskell\Qaskell\src\Example.hs:8:10-38
• In the expression: x
In an equation for ‘exFunc’: exFunc (Extype x) = x
In the instance declaration for ‘Exclass (Extype b)’
Why can type a and b not equal to each other in this case? In foldr, the accumulation function signature is (a->b->b), but it would also take f::a->a->a. Why is it that in this case, the compiler complains? Is there a way to resolve this without declaring a higher-kinded typeclass? Any information is appreciated.
Exclass
's methodexFunc
to work for anya
providingNum a
. But then your instance only works for ana
that's the same as theb
parameter toExtype
. That's not just anya
. Do you want thea
to be derive from the instance's type like that? Then you want to determinea
from the class'sc
via aTypeFamily
. (Or possiblyFunctionalDependencies
.) – AntC