简体   繁体   English

数据记录的类约束

[英]Class constraints for data records

I have a data type : 我有一个data类型:

data BuildException a = KillBuild JobID a Stage
                      | FailBuild JobID a Stage
                      | CancelBuild JobID a Stage
                      | StopBuild JobID a Stage
                         deriving Typeable

where a has to have an instance for class Foo. 其中必须具有类Foo的实例。 I remember reading (in RWH, maybe) that while it was possible to have class constraints in a data definition, it was not desirable. 我记得读过(也许是在RWH中),尽管在data定义中可能有类约束,但这并不是可取的。 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

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! 甚至有些功能不需要Foo约束,这可能使您的API客户端可以使用它的子集而不必定义Foo约束! That wouldn't be possible if it was part of the data record definition. 如果它是数据记录定义的一部分,那将是不可能的。

You read correctly. 您阅读正确。 However, in Haskell 2010, this feature was removed because it was useless. 但是,在Haskell 2010中,此功能无用,因此已删除。 You could specify the constraint in the data type, but all functions also had to have the same constraint so there was really no point. 可以在数据类型中指定约束,但是所有函数还必须具有相同的约束,因此实际上没有意义。 Thus, the feature was removed because it was completely useless. 因此,该功能已被删除,因为它完全没有用。

As said, you should just specify the constraints in the function. 如前所述,您应该只在函数中指定约束。 However, you should realize that you need not specify the constraint for a function that does not need it. 但是,您应该意识到不必为不需要约束的功能指定约束。 In particular, creation functions don't necessarily need to be limited to the constraint if not necessary, because an unlimited function like that is a generalization of the constrained version. 特别是,如果没有必要,则创建函数不必一定限于约束条件,因为像这样的无限制函数是受约束版本的泛化。 This applies to functions taking it as an argument, but such a function is much more likely to actually need the constraint. 这适用于将其作为参数的函数,但是这样的函数实际上更有可能需要约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM