Haskell 种类和类型约束

标签 haskell ghc

假设我有以下类型类

class Silly (t :: * -> *) where
    -- details

我希望能够表达以下约束,但我不确定它是否可能。

class (Silly s) => Willy (s t) where
    -- details

基本上我想对类型构造函数施加约束,而不是整个类型。这还可以表达吗?我什至不确定这种约束会被称为什么,所以 Google 没有提供任何帮助。

编辑:我有一个数据类型

data Reasoner logic atoms a = Reasoner { unReasoner :: MassAssignment atoms -> a }

有一个 Applicative 实例。我最初有一个 run 函数,以便更轻松地使用这些 Reasoners,但由于我想利用应用程序的自由可组合性,我定义了一个包含 run< 的类型类 相反,ala

class RunReasoner r where
    type MassType r
    type ResultType r
    run :: r -> MassType r -> ResultType r

具有以下实例

instance RunReasoner (Reasoner l as a) where
    type MassType (Reasoner l as a) = MassAssignment as
    type ResultType (Reasoner l as a) = a
    run = -- details

instance (RunReasoner (r2 t)) => RunReasoner (Compose (Reasoner l1 as1) r2 t) where
    type MassType (Compose (Reasoner l1 as1) r2 t) = MassAssignment as1
    type ResultType (Compose (Reasoner l1 as1) r2 t) = r2 t
    run = -- details

这样我就可以编写如下代码

expression `run` mass1 `run` mass2 `run` ... `run` massN

这在大多数情况下都很好,但我现在正在以其他方式编写推理器,并且希望 MassType 可以仅从类型构造函数 Reasoner l as 中获得,而不是必须将完整类型实例 Reasoner l 作为 a。因此,我正在考虑将 RunReasoner 类型类分成两个,因为 MassType 不依赖于最终类型参数。

最佳答案

您可以创建一个独立的类型系列

type family MassType (r :: * -> *)
type instance MassType (Reasoner l as) = as

关于Haskell 种类和类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20226902/

相关文章:

math - 在Haskell中获取平方根的整数部分

function - 为什么 foldr 可以采用具有三个参数的函数?

haskell - 如何让 GHC 为上下文中具有 Typeable 的 GADT 生成 Data.Typeable 实例?

haskell - 数据提升语法

haskell - 名义类型角色和数据系列

haskell - Haskell是否有内在的“垃圾成本”?

debugging - 让 "trace"像 "assert"一样优化?

haskell - 为什么这个 Parsec 解析器会进入无限循环?

haskell - 使用 GHCJS 和 Haskell Stack 将 Haskell 编译为 JavaScript

haskell - SPECIALIZE 编译用语的误解