小编Bor*_*ris的帖子

如何对相关数据设置约束?

我想声明关联数据始终是某个类的实例.

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

instance Context (Associated a b) where
  func1 = error "func1"
Run Code Online (Sandbox Code Playgroud)

但是,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
Run Code Online (Sandbox Code Playgroud)

是否存在一种惯用的方法来对关联数据类型进行约束,这些数据类型具有头部未提及的变量?

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

haskell type-constraints type-families

14
推荐指数
2
解决办法
715
查看次数

如何规避GHC阶段限制?

我正在编写一个代码生成器,其输出依赖于存储在其类实例中的数据类型字段描述.但是,我找不到如何使用TH生成的参数运行函数.

{-# LANGUAGE TemplateHaskell, ScopedTypeVariables #-}
module Generator where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax

data Description = Description String [Description] deriving Show

class HasDescription a where
  getDescription :: a -> Description

instance HasDescription Int where
  getDescription _ = Description "Int" []

instance (HasDescription a, HasDescription b) => HasDescription (a, b) where
  getDescription (_ :: (a, b)) = Description "Tuple2" [getDescription (undefined :: a), getDescription (undefined :: b)]

-- | creates instance of HasDescription for the passed datatype changing descriptions of its …
Run Code Online (Sandbox Code Playgroud)

haskell template-haskell

9
推荐指数
2
解决办法
1304
查看次数

默认约束种类被忽略

定义默认约束时遇到了一个奇怪的问题.如果约束是单位,则不选择默认实例.在所有其他情况下,它按预期工作.

{-# LANGUAGE TypeFamilies, ConstraintKinds #-}
import qualified GHC.Exts as E

class Expression a where
  type Constr a v :: E.Constraint
  --type Constr a v = ()         -- with this line compilation fails
  --type Constr a v = v ~ v      -- compiles
  wrap :: Constr a v => a -> Maybe v

instance Expression () where
  wrap () = Just undefined

main = print (wrap () :: Maybe Int)
Run Code Online (Sandbox Code Playgroud)

有人可以澄清类型检测器行为的原因吗?

haskell default type-constraints

9
推荐指数
1
解决办法
306
查看次数