
On Mon, Mar 23, 2009 at 09:02:56PM -0500, Zachary Turner wrote:
Everything I've read has said that it's generally considered good practice to specify the full type of a function before the definition. Why is this?
I've written some reasons not too long ago: http://www.haskell.org/pipermail/beginners/2009-February/001045.html Note that catching errors is probably the most useful benefit of writing type signatures. For a simple example, see
-- f :: Int -> Int f n = (n * 45 + 10) / 3
Do you see the problem? I've used (/) while I meant `div`. But, suppose you didn't write any type signature at all, the code would compile just fine with type 'f :: Floating a => a -> a'. Now, in another module you say
-- Type signature needed here to select what Read instance you want getNum :: IO Int getNum = read `fmap` getLine
-- doF :: IO () doF = getNum >>= print . f
Try it for yourself, what error message you get? The usual cryptic one about "Fractional Int" but *in the definition 'doF'*. Your *programmer mistake* propagated to another *module*. That is a bad, bad thing. Whenever you write type signatures, all these kinds of errors get contained inside the function they were written, saving you a lot of time. The second most important benefit probably would be to help you write the function itself. If you can't write the signature of your function, then you can't write your function at all. And it is not uncommon, even among experienced Haskellers, to write a type signature and then realise they were trying to do something completely wrong! Unfortunately I can't give you any example right now, but believe me. -- Felipe.