简体   繁体   English

如何在GHC中使用像`HasDynFlags m`这样的类型类

[英]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: 我的问题是:

  • For HasDynFlags m , does m have to be at least Functor to make this typeclass useful? 对于HasDynFlags mm是否必须至少是Functor才能使此类型类有用?
  • If the answer to the first question is no, then how are we supposed to get access to a value of DynFlags given getDynFlags :: m DynFlags , without any further knowledge about m ? 如果回答的第一个问题是否定的,那么,到底我们应该怎么去获取的值DynFlagsgetDynFlags :: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM