haskell - 如何对关联数据进行约束?

标签 haskell type-constraints type-families

我想说的是,关联的数据始终是某个类的实例。

class (Context (Associated a b)) => Class a where
  data Associated a :: * -> *

instance Context (Associated a b) where
  func1 = error "func1"

但是,自由变量 b这不在范围内,这使我无法做到这一点。一种解决方案是从 Context 复制类函数。 ,但它看起来很难看。
class Class a where
  data Associated a :: * -> *
  -- duplicate all functions from class Context
  contextFunc1 :: Associated a b -> String

instance Class a => Context (Associated a b) where
  func1 = contextFunc1

是否有一种惯用的方法来对具有头中未提及的变量的关联数据类型施加约束?

编辑:我想保持与 GHC 7.0.3 的兼容性

最佳答案

pointed out by @SjoerdVisscher 一样, 使用 forall=> 的左侧在 classinstance is actually not ok ,至少现在还没有,尽管我的具体示例在 ghc-7.4 中确实有效。

这样它似乎工作:

{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE TypeFamilies         #-}
{-# LANGUAGE Rank2Types           #-}
{-# LANGUAGE ConstraintKinds      #-}
{-# LANGUAGE UndecidableInstances #-}

class Context c where
  func1 :: c -> String

class (forall b. Context (Associated a b)) => Class a where
  data Associated a :: * -> *

newtype ClassTest = ClassTest { runClassTest :: String }

instance (forall b. Context (Associated ClassTest b)) => Class ClassTest where
  data Associated ClassTest b = ClassTestAssoc b (b -> ClassTest)

instance Context (Associated ClassTest b) where
  func1 (ClassTestAssoc b strFunc) = runClassTest $ strFunc b

main = putStr . func1 $ ClassTestAssoc 37 (ClassTest . show)

额外的forall b实例中的约束似乎有点丑陋和多余,但显然这是必要的。

$ runghc-7.4.1 tFamConstraint0.hs
37

关于haskell - 如何对关联数据进行约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11258536/

相关文章:

haskell - 为什么Guard基于Alternative?

C# 是否可以创建可选的泛型类型约束

generics - 是否可以对泛型类型进行多种类型约束?

scala - 通过将类型参数与参数的路径相关类型进行匹配来约束操作

haskell - 为什么 GHC 不会减少我的类型族?

haskell - 使用来自类型级别 map 的额外信息装饰类型级别列表

haskell - 了解类型族

haskell - 在 Haskell 中创建 MIDI 文件

haskell - 使用 `as` 语法的惰性模式匹配的语法

list - 反转列表的前 k 个元素