Class Constraints for Data Records

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 

where a must have an instance for the class Foo. I remember reading (in RWH, perhaps) that while it was possible to have class restrictions in the definition of data , this was undesirable. What is the right way to do this?

+2
source share
2 answers

Just apply type restrictions to functions that need it. For instance:

 makeException :: Foo a => String -> BuildException a 

There may even be some functions that do not need a Foo constraint, which may allow your API client to use a subset of it without the need to define a Foo constraint! This would not be possible if it were part of the definition of a data record.

+5
source

You are reading correctly. However, in Haskell 2010, this feature was removed because it was useless. You can specify a restriction in the data type, but all functions should also have the same restriction, so there really is no point. Thus, the function was removed because it was completely useless.

As said, you should just specify the restrictions in the function. However, you should understand that you do not need to specify a restriction for a function that it does not need. In particular, the creation functions need not be limited to a restriction if it is not necessary, because an unlimited function like this is a generalization of a limited version. This applies to functions that take it as an argument, but such a function is much more likely to require limitation.

+1
source

Source: https://habr.com/ru/post/988355/


All Articles