user2428836
user2428836

Reputation:

Deconstruction of type in typeclass definition (Haskell)

I'm not sure if the title is descriptive enough but I'm not very experienced in Haskell. I want to make a typeclass for two-parameter type constructors that depends on the types by which the constructor is parametrized, like

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

(assuming ctor :: * -> * -> *, a :: *, b :: *) and, assuming I have a

data Pair a b = Pair a b

be able to do something like

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

is it possible without multiple parameter type classes (because it's too powerful -- I just want to deconstruct the type my typeclass is parametrized by)?

Upvotes: 6

Views: 311

Answers (1)

Ingo
Ingo

Reputation: 36339

Yes, you can use so called "constructor classes" that take higher kinded types:

class C ctor where
    funct :: ctor a b -> a

instance C Pair where
    funct (Pair x _) = x

instance C (,) where
    funct = fst     -- (a,b) -> a

Upvotes: 7

Related Questions