【问题标题】:Haskell DerivingVia on multi param type classes with fun depsHaskell DerivingVia 上的多参数类型类与有趣的 deps
【发布时间】:2018-10-26 13:13:00
【问题描述】:

我正在尝试使用DerivingVia 为具有函数依赖关系的多参数类型类的实例定义削减样板。

我有这些类型和类:

{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DerivingVia #-}

newtype Wrapper t = Wrapper t  
newtype Wrapper2 t = Wrapper2 t

class MyEq a f | a -> f where
  eq :: a -> a -> f Bool

-- Instance for 'Wrapper2'
instance Eq t => MyEq (Wrapper2 t) Wrapper2 where
  eq (Wrapper2 t) (Wrapper2 t') = Wrapper2 (t == t')

我想使用deriving via 导出MyEq (Wrapper Int) Wrapper。

我的第一次尝试是使用:

deriving via Wrapper2 instance MyEq (Wrapper Int) Wrapper

正如论文第 6.2 节 https://www.kosmikus.org/DerivingVia/deriving-via-paper.pdf 中所讨论的,这会查找 MyEq (Wrapper Int) Wrapper2 实例,第二个参数已“更改”但第一个参数仍然是 Wrapper Int。

显然instance MyEq (Wrapper Int) Wrapper2 不存在,因为我实现了instance MyEq (Wrapper2 Int) Wrapper2。

我不能通过创建来“作弊”(参见Wrapper 作为第一类参数):

-- Instance for 'Wrapper2'
instance Eq t => MyEq (Wrapper t) Wrapper2 where
  eq (Wrapper2 t) (Wrapper2 t') = Wrapper2 (t == t')

因为在这种情况下,函数依赖 Wrapper t -> Wrapper2 不受尊重。

我可以通过重写eq :: f a -> f a -> f Bool 并删除函数依赖来轻松解决此问题,但我想避免更改此 API。

【问题讨论】:

    标签: haskell deriving derivingvia


    【解决方案1】:

    所以首先,让我们重复一下,您要为您派生的实例是这个:

    instance MyEq (Wrapper Int) Wrapper where
      eq (Wrapper t) (Wrapper t') = Wrapper (t == t')
    

    我看不到一种完全按照您想要的方式派生类的方法,因为根据您自己的观察,这需要您更改两个类参数,但我们目前只能通过最后一个派生。

    一种可能性是翻转类参数,以便“重要”类参数(决定另一个的那个)成为最后一个,然后调整您派生的包装器类型以包含一些有用的信息,如下所示:

    class MyEq f a | a -> f where
      aeq :: a -> a -> f Bool
    

    函数aeq 保留相同的类型,但MyEq 的类参数被翻转。 现在Wrapper2 得到一个额外的参数,让我们在推导时指定f 的期望值:

    newtype Wrapper2 (f :: Type -> Type) t = Wrapper2 t
    

    现在Wrapper2 的实例可以在不明确指定f 的情况下定义:

    instance (Eq t, Coercible Bool (f Bool)) => MyEq f (Wrapper2 f t) where
      eq (Wrapper2 t) (Wrapper2 t') = coerce (t == t')
    

    这里需要Wrapper2中的额外参数来满足函数依赖。

    现在我们可以如下推导出所需的实例:

    deriving via Wrapper2 Wrapper Int instance MyEq Wrapper (Wrapper Int)
    

    这行得通,因为现在,GHC 正在寻找 一个instance MyEq Wrapper (Wrapper2 Wrapper Int),这与我们拥有的相匹配 提供。


    您可以使用关联类型实现相同的目的:

    class MyEq a where
      type Result a :: Type -> Type
      eq :: a -> a -> Result a Bool
    

    Wrapper2 的定义与额外的参数相同。实例变为

    instance (Eq t, Coercible Bool (f Bool)) => MyEq (Wrapper2 f t) where
      type Result (Wrapper2 f t) = f
      eq (Wrapper2) (Wrapper2 t') = coerce (t == t')
    
    deriving via Wrapper2 Wrapper Int instance MyEq (Wrapper Int)
    

    【讨论】:

    • 第二种解决方案似乎需要UndecidableInstances。
    • 不是吗? UndecidableInstances 是无害的,所以我不会担心。
    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 2013-11-10
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多