6

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)?

4

1 回答 1

7

是的,您可以使用采用更高种类的所谓“构造函数类”:

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
于 2013-07-05T14:42:16.957 回答