Haskell-具有两个参数的类型类的翻转参数 [英] Haskell - flip arguments of a typeclass with two parameters

查看:129
本文介绍了Haskell-具有两个参数的类型类的翻转参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多参数类型类,它提供了一个有意义的函数,可以将其参数互换:

I have a multiparam typeclass which supplies a function that makes sense to have its arguments swapped:

class Swappable a b where
    swappable :: a -> b -> Bool

因此,如果ab形成Swappable a b,则ba应该形成Swappable b a.为每个普通实例编写一个交换实例非常麻烦,所以我天真地写了

So if a and b form Swappable a b, then b and a should form Swappable b a. Writing a swapped instance for each normal instance would be a chore, so I naively wrote

instance Swappable a b => Swappable b a where
    swappable b a = swappable a b

没有编译时出现以下错误:

Which doesn't compile with the following error:

    • Illegal instance declaration for ‘Swappable b a’
        (All instance types must be of the form (T a1 ... an)
         where a1 ... an are *distinct type variables*,
         and each type variable appears at most once in the instance head.
         Use FlexibleInstances if you want to disable this.)
    • In the instance declaration for ‘Swappable b a’
   |
12 | instance Swappable a b => Swappable b a where
   |                           ^^^^^^^^^^^^^

现在,我并不反对打开FlexibleInstances,但是我不明白为什么我首先需要它.那里的所有类型变量都出现一次,并且都是不同的.那么为什么会出现此错误?

Now, I'm not really averse to turning on FlexibleInstances, but I don't understand why I need it in the first place. All type variables there appear once, and are all distinct. So why do I get this error?

推荐答案

All instance types must be of the form (T a1 ... an)

意味着您的实例必须采用以下形式

Means that your instance must be of the form

instance Swappable (T a1 .. an) (U b1 .. bn) where ...

其中,TU是类型构造函数.如果没有该扩展名,就不能只有一个变量ab,而没有顶部的构造函数.

where T and U are type constructors. Without that extension, you can not have only single variables a and b without a constructor on top.

FlexibleInstances是无害的,并且可以说默认情况下应该将其打开.也许将来的《 Haskell报告》修订版将包含该报告.

FlexibleInstances is harmless, anyway, and should arguably turned on by default. Maybe a future revision of the Haskell Report will include it.

相反,我会更担心重叠. instance Swappable b a => Swappable a b将与任何其他实例重叠.它还将需要无法确定的实例.我不确定您要达到的目标是一个好主意.

I would be far more concerned by the overlapping, instead. instance Swappable b a => Swappable a b will overlap with any other instance. It will also require undecidable instances. I'm not sure about what you are trying to achieve is a good idea.

这篇关于Haskell-具有两个参数的类型类的翻转参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆