我已经将头撞墙了一段时间了。我有一堆类型,它们表示对基本类型的转换(更具体地说,XMonad中的布局修饰符)。

长话短说,这些类型都有种(* -> *) -> * -> *

出于我在这里不想真正讨论的原因,我想做的是获取这些转换的堆栈,并将它们表示为基于基本类型(* -> *)的单个转换。

我的第一个想法是定义类型组合运算符

newtype ((f :: (* -> *) -> * -> *) :. (g :: (* -> *) -> * -> *)) l a
        = Compose (f (g l) a)

它在大多数情况下都有效。但是,给定一个值v :: f1 (f2 (f3 (... (fn l))) a,我必须对其应用Compose n-1次才能获得v' :: (f1 :. f2 :. ... :. fn) l a,这不是很漂亮,也很烦人。

所以,问题是,有没有办法自动应用Compose直到得到我想要的东西?

例如,现在我做这样的事情:
modifyLayout $ Compose . Compose . Compose . Mirror . avoidStruts .  minimize . smartBorders

我想做的事:
modifyLayout' $ Mirror . avoidStruts . minimize . smartBorders
    where modifyLayout' = modifyLayout . magicCompose

一个相关的问题:也许有更好的方法来表达相同的概念?

作为引用,modifyLayout
modifyLayout :: (CC m Window)
          => (forall l. (LayoutClass l Window) => l Window -> m l Window)
          -> ConfigMonad

澄清(EDIT):

使用类型组合背后的整个想法是这样的。

考虑两个布局修饰符,
m1 :: LayoutClass l a => l a -> M1 l a


m2 :: LayoutClass l a => l a -> M2 l a

如果我将这两个组成,
m1m2 :: (LayoutClass l a, LayoutClass (M2 l) a) => l a -> M1 (M2 l) a
m1m2 = m1 . m2

我们可以假设存在一个instance LayoutClass l a => LayoutClass (M2 l) a。同时,还假设存在CC M1 WindowCC M2 Window的实例。

如果我现在尝试将其输入到上面定义的modifyLayout中:
modifyLayout m1m2

GHC立即被嵌套类型弄糊涂并抱怨:
Couldn't match type ‘l’ with ‘M2 l’
  ‘l’ is a rigid type variable bound by
      a type expected by the context:
        LayoutClass l Window => l Window -> M1 l Window
Expected type: l Window -> M1 l Window
  Actual type: l Window -> M1 (M2 l) Window

使用类型组合,我可以纠正这一点,因为GHC将M1 :. M2m签名中的modifyLayout匹配,并避免了整个嵌套的困惑。类型同义词显然没有此属性。

更新:

经过一番戳后,我找到了部分解决方案(不知道为什么我不早想到它,但是哦)

可以这样定义一个类型类
class S l f t | f l -> t where
  sq :: (l a -> f a) -> (l a -> t l a)

功能依赖性确保编译器能够自行选择实例。

然后,可以编写这样的实例
instance S l (m1 l) m1 where
  sq = id
instance S l (m1 (m2 l)) (m1 :. m2) where
  sq = sq . (Compose .)
instance S l (m1 (m2 (x l))) ((m1 :. m2) :. x) where
  sq = sq . (Compose .)
instance S l (m1 (m2 (m3 (x l)))) (((m1 :. m2) :. m3) :. x) where
  sq = sq . (Compose .)
-- etc

这部分回答了我的问题:sq封装了一个转换栈,只要为给定的嵌套级别定义了一个实例即可。

但是,这些实例似乎请求递归实例定义。到目前为止,我还无法弄清楚它的外观如何。因此,欢迎有识之士。

最佳答案

感谢Adam Vogt(@aavogt),我终于能够得出令人满意的结论。

我在使用S类的实例时步入正轨。事实证明,反向实例依赖关系允许typechecker推断其他实例。但是,递归终止需要IncoherentInstances扩展名(即基本情况)。

这是代码:

instance {-# INCOHERENT #-} S l (m l) m where
  sq = id
instance S l ((f :. g) l') t => S l (f (g l')) t where
  sq = squash . (Compose .)

08-05 05:18
查看更多