gpt4 book ai didi

haskell - 是否可以使 (a, a) 成为 Haskell 中类型类的成员

转载 作者:行者123 更新时间:2023-12-02 16:02:36 27 4
gpt4 key购买 nike

这是 Haskell 中的代码:

class Fooable a where
foo :: a -> a

instance Fooable (a, a) where
foo = ...

如果没有 FlexibleInstances 扩展,这样的代码将无法在传统 Haskell 中编译。错误消息会显示:

Illegal instance declaration for ‘Fooable (a, 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 ‘Fooable (a, a)’

问题是,实际上不可能使元组 (a, a) 成为任何类型类的成员,因为每个类型变量在实例头中最多出现一次?

最佳答案

没有办法直接在实例中强制执行 (a, b) 的关系(没有 FlexibleInstances 或其他扩展),但它们可能是等价。

这意味着如果 Fooable (a, b) 是一个实例,那么如果 a 可以等于 b,则 Fooable ( a,a) 也是一个实例。考虑获得更多实例。

但是,有一种解决方法:

newtype Tuple a = Tuple {unTuple :: (a, a)}

instance Fooable (Tuple a) where
foo = id

这不是地球上最漂亮或最好的东西,但至少在运行时它的行为就像没有包装器一样。

关于haskell - 是否可以使 (a, a) 成为 Haskell 中类型类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32593576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com