Deconstructing a Type in a Class Definition (Haskell)

I'm not sure the title is descriptive enough, but I'm not very experienced at Haskell. I want to create typeclass for constructors with two parameters, which depend on the types with which the constructor is parameterized, for example

class MyTypeclass (ctor ab) where funct :: (ctor ab) -> a 

(assuming ctor :: * -> * -> * , a :: * , b :: * ) and assuming that <

 data Pair ab = Pair ab 

able to do something like

 instance MyTypeclass (Pair ab) where funct :: Pair ab -> a funct (Pair x _) = x 

Is this possible without several classes of parameter types (because it is too powerful - I just want to deconstruct the type that my typeclass is parameterized)?

+6
source share
1 answer

Yes, you can use the so-called constructor classes that accept higher type types:

 class C ctor where funct :: ctor ab -> a instance C Pair where funct (Pair x _) = x instance C (,) where funct = fst -- (a,b) -> a 
+7
source

Source: https://habr.com/ru/post/948792/


All Articles