Search code examples
haskelltypeclassnewtype

How to state that a type variable in a newtype statement is of a type that belongs to some type class?


Suppose that I have this newtype:

newtype SomeType a = SomeType { foo :: OtherType a }

I want to ensure that a is showable (belongs to the type class Show x).

How do I ensure that? (Is it even possible?)

Bonus points: am I using the terminology correctly?


Solution

  • It is possible with the DatatypeContexts extension, but it is strongly discouraged:

    newtype Show a => SomeType a = SomeType { foo :: Maybe a }
    

    It is recommended to put the constraint on the functions that use SomeType or use GADTs. See the answers to these questions for more information.

    Alternative for deprecated -XDatatypeContext?

    DatatypeContexts Deprecated in Latest GHC: Why?

    Basically, it doesn't add anything useful and it makes you have to put constraints where they wouldn't otherwise be necessary.