Difference between revisions of "Type signatures as good style"

From HaskellWiki
Jump to navigation Jump to search
(→‎Answer: link to type signature)
(Deleting page that hasn't been edited for over 10 years)
Line 1: Line 1:
== Question ==
 
 
Since Haskell type checkers can automatically [[Determining_the_type_of_an_expression|derive types of expressions]]
 
why shall I put explicit type signatures in my programs?
 
 
== Answer ==
 
 
Using explicit [[type signature]]s is good style and [[GHC]] with option <code>-Wall</code> warns about missing signatures.
 
Signatures are a good documentation and not all Haskell program readers have a type inference algorithm built-in.
 
There are also some cases where the infered signature is too general for your purposes.
 
E.g. the infered (most general) type for <hask>asTypeOf</hask> is <hask>a -> b -> a</hask>,
 
but the purpose of <hask>asTypeOf</hask> is to unify the types of both operands.
 
The more special signature <hask>a -> a -> a</hask> is what you want and it cannot be infered automatically.
 
Another example:
 
<haskell>
 
emptyString :: ShowS
 
emptyString = id
 
</haskell>
 
Where <hask>ShowS</hask> is <hask>String -> String</hask> rather than <hask>a -> a</hask>.
 
 
Even more, for some type extensions the automatic inference fails,
 
e.g. the higher-order types used by <hask>Control.Monad.ST.runST</hask>
 
<haskell>
 
runST :: (forall s . ST s a) -> a
 
</haskell>
 
cannot be inferred in general, because the problem is undecidable. In GHC, they are enabled with the language pragma <code>RankNTypes</code>.
 
 
== How to add a bunch of signatures? ==
 
 
Ok, this convinced me. How can I add all the signatures I did not write so far?
 
 
: You can start [[GHC|GHCi]] or [[Hugs]] and use the <code>:browse Modulename</code> directive. This will list all type signatures including the infered ones.
 
 
 
 
[[Category:FAQ]]
 
[[Category:Style]]
 

Revision as of 14:10, 6 February 2021