是否可以将其他类型变量引入超类约束? [英] Is it possible to introduce additional type variables into a superclass-constraint?

查看:121
本文介绍了是否可以将其他类型变量引入超类约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理类型族时,通常使用等号约束来避免在签名中重复某些类型函数的名称:

  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 - > mf

即使缩写未在签名本身中出现, 。

对于类,这显然是不可能的;

  class (Foo f,b〜BulkyAssociatedType f,Monoid b,...)=> Bar f 

抱怨类型变量 b 不是



是否有某种方法可以实现类似的目的,避免一些重复 - 样板文件?

解决方案

令我感到惊讶的是,我不知道你做了什么(我使用过相同的技术,并且知道它在 instance 声明中有效),但是似乎是一个长期的 GHC功能请求来支持这一点。

也许你可以使用

  ConstraintKinds  可以获得相同的好处: > { - #LANGUAGE TypeFamilies,FlexibleContexts,ConstraintKinds# - } 
import Data.Monoid

class Foo f其中
类型BulkyAssociatedType f :: *

类型B f =(Monoid(BulkyAssociatedType f))

class(Foo f,B f)=> Bar f


When dealing with type families, it is often handy to use equality constraints to avoid having to repeat some type-function's name in a signature:

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

This works even if the abbreviation doesn't turn up in the signature itself, only in the constraints.

With classes, this is apparently not possible;

class ( Foo f, b ~ BulkyAssociatedType f, Monoid b, ...) => Bar f

complains about type variable b not being in scope.

Is the some way to achieve a similar thing, to avoid a bit of repetition-boilerplate?

解决方案

It surprised me to learn you can't do that (I've used the same technique and know it works in instance declarations), but there seems to be a long-standing GHC feature request to support this.

Maybe you can use ConstraintKinds to get the same benefit:

{-# 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

这篇关于是否可以将其他类型变量引入超类约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆