4

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?

Lay González
  • 2,901
  • 21
  • 41

2 Answers2

4

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.

Community
  • 1
  • 1
David Young
  • 10,713
  • 2
  • 33
  • 47
3

To demonstrate @David's answer in a small example, imagine you're implementing another incarnation of a balanced binary tree. Of course keys must be Ordered, so you add a constraint to the type declaration:

data Ord k => Tree k v = Tip | Bin k v (Tree k v) (Tree k v)

Now this constraint infects every other signature everywhere you're using this type, even when you don't really need to order keys. It wouldn't probably be a bad thing (after all, you'll need to order them at least somewhere – otherwise, you aren't really using this Tree) and it definitely doesn't break the code, but still makes it less readable, adds noise and distracts from important things.

empty :: Ord k => Tree k v

singleton :: Ord k => k -> v -> Tree k v

find :: Ord k => (v -> Bool) -> Tree k v -> Maybe v

instance Ord k => Functor (Tree k)

In all of these signatures the constraint could be omitted without any problems.

Yuuri
  • 1,858
  • 1
  • 16
  • 26