Haskell 可以合并typeclass的实例吗?
我觉得这是不可能的,但我希望能提供一些信息,看看我是否缺少一些扩展或技术 我有一个typeclass的通用实例,它定义了一些默认方法:Haskell 可以合并typeclass的实例吗?,haskell,Haskell,我觉得这是不可能的,但我希望能提供一些信息,看看我是否缺少一些扩展或技术 我有一个typeclass的通用实例,它定义了一些默认方法: class TestClass a where foo :: a -> Maybe Text bar :: a -> [Int] instance TestClass a where foo _ = Nothing bar _ = [] data SpecificType = SomeValue | OtherValue
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"
我相信这已经需要
重叠实例
,但问题是SpecificType
的TestClass
实例没有实现bar
。我只想声明第二个实例的一部分,其余部分使用默认实现。有没有办法做到这一点 在Haskell 98中,您可以放入类
定义:
class TestClass a where
foo :: a -> Maybe Text
foo _ = Nothing -- default implementation
bar :: a -> [Int]
bar _ = [] -- default implementation
class TestClass a其中
foo::a->Maybe Text
foo\uz=Nothing——默认实现
bar::a->[Int]
条形图=[]--默认实现
现在,对于您自己没有实现
foo
或bar
的所有实例
s,它将采用默认实现。还有其他方法组合实例吗?不可否认,我的用例比我介绍的更复杂。例如,如果默认实例也需要Show
,该怎么办?(instance Show a=>TestClass a where…
@jkeuhlen那么,问一个更具体的问题。@leftaroundabout:我可能会,但我也从这个答案中学到了一些东西,这对问题的回答很有帮助,所以我不打算在没有先跟进的情况下编辑当前问题或问一个新问题。@jkeuhlenDefaultSignatures
允许您使用更具体的类型声明默认值。@BenjaminHodgson这正是我想要的,谢谢!如果您想添加答案,或将其编辑到WillemVanOnsem的答案中(经批准)我认为它应该比评论更高一级。谢谢!它已经在主答案的链接中了,但是你必须寻找它。我甚至没有意识到扩展的存在。