【问题标题】:type families and deriving instances (Eq)类型族和派生实例 (Eq)
【发布时间】:2016-07-28 19:47:04
【问题描述】:

如果有额外的帮助,是否可以为B a 派生 Eq 实例,例如Eq a 某处?

{-# LANGUAGE TypeFamilies #-}

class A a where
  type B a 
  somef :: a -> B a -> B a -> Bool

问题deriving instances with type familiesinstance definitions for type families 很接近。 以下在type B a -line 上不起作用或类似的修改(或者只是尝试了错误的修改)。

{-# LANGUAGE StandaloneDeriving #-}
-- deriving instance Eq (B a) -- illegal application
-- deriving instance Eq a => Eq (B a) -- illegal application

约束 Eq a => A a 没有帮助。将约束添加到 somef 编译 (somef :: Eq a => ...) 并适用于此方法。但是,在这种情况下,如果能够判断 type B a 通常是可等式的(这样就不允许使用不可等式的 B a),而不是逐个方法。

【问题讨论】:

  • 您希望能够限制类实例为自己键入 Eq 的实例?
  • 是的,能够将 B a 类型实例限制为本身就是 Eq 实例的类型。

标签: haskell type-families


【解决方案1】:

我认为这可以解决问题...

{-# LANGUAGE TypeFamilies, FlexibleContexts #-}

class Eq (B a) => A a where
  type B a 
  somef :: a -> B a -> B a -> Bool

作为验证它的工作,以下实例被接受

data HasEqInstance = HasEqInstance deriving Eq
instance A () where
  type B () = HasEqInstance
  somef = undefined

但是这个被No instance for (Eq NoEqInstance)拒绝

data NoEqInstance = NoEqInstance
instance A () where
  type B () = NoEqInstance
  somef = undefined

【讨论】:

  • 荣誉,现在看起来很清楚(我正在向类型家族迈出第一步)。
猜你喜欢
  • 2013-08-31
  • 2020-04-01
  • 2016-01-06
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 2014-10-02
  • 1970-01-01
  • 2023-03-19
相关资源
最近更新 更多