Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't one put type signatures in instance declarations in Haskell?

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?

like image 601
Prateek Avatar asked Dec 03 '11 11:12

Prateek


People also ask

What is type signature in Haskell?

From HaskellWiki. A type signature is a line like. inc :: Num a => a -> a. that tells, what is the type of a variable. In the example inc is the variable, Num a => is the context and a -> a is its type, namely a function type with the kind * -> * .

What are instances in Haskell?

An instance of a class is an individual object which belongs to that class. In Haskell, the class system is (roughly speaking) a way to group similar types. (This is the reason we call them "type classes"). An instance of a class is an individual type which belongs to that class.


3 Answers

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 = ...
like image 28
hugomg Avatar answered Oct 24 '22 05:10

hugomg


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.

like image 158
crockeea Avatar answered Oct 24 '22 06:10

crockeea


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 #-}
like image 12
JonnyRaa Avatar answered Oct 24 '22 06:10

JonnyRaa