haskell - 在 Haskell 中,是否可以为部分应用的多参数类型类提供默认实现?

标签 haskell default typeclass multiparameter

例如,我有一个类型类:

class MyClass a b c where
    fun01 :: a -> b
    fun02 :: a -> c

    fun03 :: a -> b -> c -> ()
    fun04 :: a -> WhatEver

我想为我的提供一个默认实现,我们称之为 BaseDataType它定义了 fun03 的实现就其自身而言,fun01fun02 .然后我会有这样的事情:
class MyClass BaseDataType b c where
    fun03 = fun01 <$> fun02 ...
    fun04 = fun02 ...

而不是完成我的类实例并避免 fun03 的所有样板代码和 fun04我只提供 fun01fun02像这样 :
instance MyClass BaseDataType Int Char where
    fun01 = 1
    fun02 = 'C'

是否有一些语言扩展允许这种行为?我找不到有关此主题的任何内容。

最佳答案

没有这样的扩展,但您只需将您的类分成两个类即可实现此功能:

class MyClass1 a b c where
    fun03 :: a -> b -> c -> ()
    fun04 :: a -> WhatEver

class MyClass1 a b c => MyClass2 a b c where    
    fun01 :: a -> b
    fun02 :: a -> c

然后您的实例将按照您想要的方式工作:
-- NB: need the MyClass2 constraint if you use `fun01` or `fun02` in the definitions
-- This requires UndecidableInstances
instance MyClass2 BaseDataType b c => MyClass1 BaseDataType b c where
    fun03 = fun01 <$> fun02 ...
    fun04 = fun02 ...

instance MyClass2 BaseDataType Int Char where
    fun01 = 1
    fun02 = 'C'

您类(class)的用户不受影响;他们可以继续消费MyClass2他们在哪里使用MyClass之前并获得完全相同的功能。

旁白:MyClass 的原始定义, 和 MyClass1MyClass2由于几个模棱两可的类型错误( c 的类型中没有提到 fun01 等),甚至不编译 - 我假设这个类只是为了演示目的而定义的,我没有尝试修复这个问题。

关于haskell - 在 Haskell 中,是否可以为部分应用的多参数类型类提供默认实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47872101/

相关文章:

haskell - 制作 PersistBackend 的自定义实例

JSF 复合组件支持 bean EL 表达式作为必需属性的默认值失败,方法未知

java - 为注释字段设置默认空值时出错

Haskell:安全 'show'

scala - 如何让 scala 编译器从一种类型推断另一种类型?

haskell - 类声明和实例声明之间有什么区别?

list - Haskell:在类型系统中指定列表的等长约束

haskell - 如何编译依赖项以在 cabal 沙箱中进行分析

Haskell:从 Data.Random 中的 RVar 中获取值

django - 自定义 radioselect 默认渲染器