20
votes

I like to put type signatures for all top-level definitions in my code. However, type signatures in instance declarations don't seem to be allowed, and if I put one I get a "Misplaced type signature" error from GHC. Why is this so? Why can't GHC check if the type signature is the same as what it was expecting, and reject (or warn) if it isn't?

5
On the ticket I opened SPJ commented: "I've wanted [type signatures in instance declarations] myself, so I've done it in a spare moment." He currently set the milestone to GHC 7.6, though there is a slight chance it will make it into GHC 7.4. Thanks for asking this question! And thanks, Daniel Fischer, for suggesting that we make a ticket.Dan Burton

5 Answers

14
votes

You can add type signatures for instances using [the new] -XInstanceSigs, which is especially useful for bringing type variables in scope. You can find more information in the official docs.

12
votes

You can create the functions separately, outside the instance body, if you really want the type declarations.

class Class a where
    f1 :: a -> a

instance Class Foo where
    f1 = foo_f1

--monomorphic version of f1 for Foo:
foo_f1 :: Foo -> Foo
foo_f1 = ...
11
votes

Most of the other answers here are pretty old... there's now a language extension:

stick the following at the top of your file:

{-# Language InstanceSigs #-}
5
votes

Since the signature is part of the class definition, a type signature in an instance declaration would be a duplicate signature. I don't think there's a problem with allowing duplicate signatures in principle, but there's no advantage in allowing them generally, and it's simpler to disallow them. So the language definition says there can be at most one type signature per entity. The feature of allowing signatures also in instance declarations hasn't been asked for much, so there's no extension allowing it. If you really want that, you can raise a feature request on the GHC trac. If it gets enough interest, it may be implemented (but I don't expect the demand to be high).

2
votes

In any case, the type is redundant and one normally wants to avoid redundancies. In Frege, it is nevertheless allowed to write type signatures for instance members. They are checked and then thrown away. It's of course easier to forbid them right away.