例如,我有一个类型类:
class MyClass a b c where
fun01 :: a -> b
fun02 :: a -> c
fun03 :: a -> b -> c -> ()
fun04 :: a -> WhatEver
我想为我的提供一个默认实现,我们称之为
BaseDataType
它定义了 fun03
的实现就其自身而言,fun01
和 fun02
.然后我会有这样的事情:class MyClass BaseDataType b c where
fun03 = fun01 <$> fun02 ...
fun04 = fun02 ...
而不是完成我的类实例并避免
fun03
的所有样板代码和 fun04
我只提供 fun01
和 fun02
像这样 :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
的原始定义, 和 MyClass1
和 MyClass2
由于几个模棱两可的类型错误( c
的类型中没有提到 fun01
等),甚至不编译 - 我假设这个类只是为了演示目的而定义的,我没有尝试修复这个问题。
关于haskell - 在 Haskell 中,是否可以为部分应用的多参数类型类提供默认实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47872101/