是否可以组合类型类的实例?

jke*_*len 2 haskell

我有一种感觉,这是不可能的,但我会喜欢一些输入,看看是否有一些我缺少的扩展或技术.

我有一个类型类的通用实例,它定义了一些默认方法:

class TestClass a where 
  foo :: a -> Maybe Text 
  bar :: a -> [Int]

instance TestClass a where 
  foo _ = Nothing 
  bar _ = []

data SpecificType = SomeValue | OtherValue

instance TestClass SpecificType where 
  foo SomeValue = Just "Success"
  foo OtherValue = Just "Other Success"
Run Code Online (Sandbox Code Playgroud)

我相信这已经需要OverlappingInstances,但问题是TestClassfor 的实例SpecificType没有实现bar.我只想声明第二个实例的一部分,并使用其余的默认实现.有没有办法实现这个目标?

Wil*_*sem 6

在Haskell 98中,您可以定义中放置默认实现class:

class TestClass a where
    foo :: a -> Maybe Text 
    foo _ = Nothing  -- default implementation
    bar :: a -> [Int]
    bar _ = []       -- default implementation
Run Code Online (Sandbox Code Playgroud)

现在,对于instance您没有实现的所有内容foo或您bar自己,它将采用默认实现.

  • @jkeuhlen`DefaultSignatures`允许您使用更具体的类型声明默认值.[参见`aeson`的例子](https://github.com/bos/aeson/blob/08fcbcd6ed65d9b3d80300e2bd363bfcd76e38bd/Data/Aeson/Types/ToJSON.hs#L284) (5认同)