小编Ger*_*ood的帖子

使用 typeclass 方法的默认实现来省略参数

我希望能够定义一个(多参数)类型类实例,该实例的类方法的实现忽略其参数之一。这可以很容易地完成,如下所示。

instance MyType MyData () where
    specific _ a = f a
Run Code Online (Sandbox Code Playgroud)

由于我在多个地方使用此模式,因此我尝试通过添加专门的类方法和适当的默认实现来概括它。我想出了以下内容。

{-# LANGUAGE MultiParamTypeClasses, AllowAmbiguousTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}

class MyType a b where
    specific :: b -> a -> a
    specific = const dontCare
    dontCare :: a -> a
    dontCare = specific (undefined :: b)
    {-# MINIMAL specific | dontCare #-}
Run Code Online (Sandbox Code Playgroud)

然而,这会产生错误Could not deduce (MyType a b0) arising from a use of ‘dontCare’[..] The type variable ‘b0’ is ambiguous。我不明白为什么后者应该是类型变量b的范围从类签名到方法声明的情况。你能帮我理解这里出现的确切问题吗?

是否有另一种合理的方法来实现我的意图,即以通用方式允许此类修剪过的实例?

haskell typeclass

6
推荐指数
1
解决办法
65
查看次数

标签 统计

haskell ×1

typeclass ×1