[英]How to use a typeclass like `HasDynFlags m` in GHC
While playing with GHC code base, I find a typeclass named HasDynFlags
: 在使用GHC代码库时,我发现了一个名为
HasDynFlags
的类型类:
class HasDynFlags m where
getDynFlags :: m DynFlags
Although the typeclass name looks self-explanatory, I couldn't find other constraints in the typeclass definition that says m
has to be Monad
or at least Functor
so we can get access to that value. 尽管类型类名称看起来很不言自明,但在类型类定义中我找不到其他约束,即
m
必须是Monad
或至少是Functor
这样我们才能访问该值。
However, most use of it I find in the code base is inside a do-notation, eg dynFlag <- getDynFlags
where m
is further constrainted to be an instance of Monad
. 但是,我在代码库中发现的大多数用法都在do表示法内,例如
dynFlag <- getDynFlags
,其中m
被进一步约束为Monad
的实例。
My questions are: 我的问题是:
HasDynFlags m
, does m
have to be at least Functor
to make this typeclass useful? HasDynFlags m
, m
是否必须至少是Functor
才能使此类型类有用? DynFlags
given getDynFlags :: m DynFlags
, without any further knowledge about m
? DynFlags
给getDynFlags :: m DynFlags
,没有任何进一步的知识m
? According to the class definition, 根据类的定义,
class HasDynFlags m where
getDynFlags :: m DynFlags
m
is satisfied by kind (* -> *)
. m
由种类(* -> *)
。 The kind (* -> *)
is implied by the type m DynFlags
, which demonstrates that m
is a type constructor taking exactly one type parameter. 类型
m DynFlags
隐含了种类(* -> *)
,这表明m
是仅采用一个类型参数的类型构造函数。
There are no further constraints on m
here. 在此,
m
上没有其他限制。 Specifically, the resulting type needn't be a Functor (or Monad), although given common naming conventions for type variables in Haskell, there's a good chance Monad is the motivating case. 具体来说,虽然给定了Haskell中类型变量的通用命名约定,但生成的类型不必是Functor(或Monad),但Monad很有可能是有启发性的案例。
EDIT: To answer the second question, the Functor or Monad class constraints we expect are introduced in more specific contexts. 编辑:要回答第二个问题,我们期望在更具体的上下文中引入我们希望的Functor或Monad类约束。 For example, consider the type,
例如,考虑类型,
(HasDynFlags m, Monad m) => m DynFlags
I think that's all there is to it. 我认为这就是全部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.