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 methodexFuncto work for anyaprovidingNum a. But then your instance only works for anathat's the same as thebparameter toExtype. That's not just anya. Do you want theato be derive from the instance's type like that? Then you want to determineafrom the class'scvia aTypeFamily. (Or possiblyFunctionalDependencies.) - AntC