lef*_*out 16 haskell typeclass type-constraints type-families
处理类型族时,使用等式约束通常很方便,以避免在签名中重复某个类型函数的名称:
class Foo f where
type BulkyAssociatedType f :: *
foo :: BulkyAssociatedType f -> f
...
bar :: forall m f b .
( Monad m, Foo f, b ~ BulkyAssociatedType f
, Monoid b, Monoid (m b)
) => f -> m f
Run Code Online (Sandbox Code Playgroud)
即使缩写没有在签名本身中出现,只有在约束中才有效.
有了课程,这显然是不可能的;
class ( Foo f, b ~ BulkyAssociatedType f, Monoid b, ...) => Bar f
Run Code Online (Sandbox Code Playgroud)
抱怨类型变量b不在范围内.
有一些方法可以实现类似的东西,避免一点点重复 - 样板吗?
让我感到惊讶的是,我知道你不能这样做(我使用相同的技术,并且知道它在实例声明中有效),但似乎有一个长期的GHC功能请求来支持这一点.
也许你可以ConstraintKinds用来获得同样的好处:
{-# LANGUAGE TypeFamilies , FlexibleContexts , ConstraintKinds #-}
import Data.Monoid
class Foo f where
type BulkyAssociatedType f :: *
type B f = (Monoid (BulkyAssociatedType f))
class ( Foo f, B f) => Bar f
Run Code Online (Sandbox Code Playgroud)