2012-11-12 49 views
2

请原谅我下面可能滥用类别理论术语。如果我看起来有一半线索,我会判断自己非常成功。如何简化几个arvals类型构造函数的“产品”类型类?

我发现自己写了一系列的类来处理多个类型构造函数的产品。像这样:

import Control.Applicative 

-- | RWS monad. 
newtype RWS r w s a = RWS {runRWS :: r -> s -> (a, s, w)} 

-- | A class for unary type constructors that support a Cartesian 
-- product operation. 
class ProductObject f where 
    (***) :: f a -> f b -> f (a, b) 
infixr *** 

-- | Example instance of 'ProductObject'. 
instance ProductObject [] where 
    (***) = liftA2 (,) 


-- | A class for binary type constructors (read as morphisms 
-- between their type parameters) that support a product morphism 
-- operation. 
class ProductMorphism arrow where 
    (****) :: arrow a b -> arrow c d -> arrow (a, c) (b, d) 
infixr **** 

-- | Example instance of 'ProductMorphism'. 
instance ProductMorphism (->) where 
    f **** g = \(a, c) -> (f a, g c) 


-- | A class for ternary type constructors (read as two-place 
-- multiarrows @a, b -> [email protected]) with products. 
class ProductMultimorphism2 arr2 where 
    (*****) :: arr2 a b c -> arr2 d e f -> arr2 (a, d) (b, e) (c, f) 
infixr ***** 


-- | A class for ternary type constructors (read as two-place 
-- multiarrows @a, b -> [email protected]) with products. 
class ProductMultimorphism3 arr3 where 
    (******) :: arr3 a b c d -> arr3 e f g h -> arr3 (a, e) (b, f) (c, g) (d, h) 
infixr ****** 

-- | Let's pretend that the 'RWS' monad was not a type synonym 
-- for 'RWST'. Then an example of 'ProductMorphism3' would be: 
instance ProductMultimorphism3 RWS where 
    f ****** g = RWS $ \(fr, gr) (fs, gs) -> 
     let (fa, fs', fw) = runRWS f fr fs 
      (ga, gs', gw) = runRWS g gr gs 
     in ((fa, ga), (fs', gs'), (fw, gw)) 

现在,这是令人讨厌的几个原因。最大的问题是我必须在我的应用程序中修改其中的一种类型以添加​​第三个参数,这意味着现在我必须去查找该类型的所有用途****并将它们更改为*****

我可以申请缓解这种情况吗?我试图了解GHC中的PolyKinds是否适用于此,但(a)这很慢,(b)我听说GHC 7.4.x中的PolyKinds是buggy。

回答

0

嗯,我想通了我自己:

{-# LANGUAGE MultiParamTypeClasses, TypeFamilies #-} 

import Control.Applicative 

class Product f g where 
    type Prod a b :: * 
    (***) :: f -> g -> Prod f g 


instance Product [a] [b] where 
    type Prod [a] [b] = [(a, b)] 
    (***) = liftA2 (,) 

instance Product (a -> b) (c -> d) where 
    type Prod (a -> b) (c -> d) = (a, c) -> (b, d) 
    f *** g = \(a, c) -> (f a, g c) 
相关问题