数据记录的类限制 [英] Class constraints for data records
问题描述
我有一个 data
类型:
I have a data
type :
data BuildException a = KillBuild JobID a Stage
| FailBuild JobID a Stage
| CancelBuild JobID a Stage
| StopBuild JobID a Stage
deriving Typeable
其中a必须具有Foo类的实例。我记得阅读(也许在RWH中)
,而在 data
定义中可能有类限制,这是不可取的。
然后执行此操作的正确方法是什么?
where a has to have an instance for class Foo. I remember reading (in RWH, maybe) that
while it was possible to have class constraints in a data
definition, it was not desirable.
What's the proper way to do this then?
推荐答案
简单地将类型约束应用于需要它的函数。例如:
Simply apply the type constraints on functions that need it. For example:
makeException :: Foo a => String -> BuildException a
甚至可能有一些函数不需要 Foo
约束,这可能使API的客户端可以使用它的一个子集而不必定义 Foo
约束!这是不可能的,如果它是数据记录定义的一部分。
There might even be some functions that don't need the Foo
constraint, which might make it possible for the client of your API to use a subset of it without having to define the Foo
constraint! That wouldn't be possible if it was part of the data record definition.
这篇关于数据记录的类限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!