我想说的是,关联的数据始终是某个类的实例。
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
在 =>
的左侧在 class
或 instance
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/