I am new to Haskell and I am trying to understand why one needs to write type declarations. Since Haskell has type inference, when do I need the first line at all? GHCI seems to generate correct output with I use ‘:t’
The only example I found so far that seems to need a declaration is the following.
maximum' :: (Ord a) => [a] -> a
maximum' = foldr1 max
However, if I add “-XNoMonomorphismRestriction” flag declaration is not needed again. Are there specific situations when type inference does not work and one needs to specify types?
Since I could have a bug in type declaration and no direct benefit, I’d rather not write it. Again, I have just started learning Haskell, so please correct me if I am wrong, as I want to develop good habits.
EDIT: It turns out that the Type inference is a double-edged sword section of the Real World Haskell book has a nice discussion of this topic.
Consider
read "5". How can Haskell know the type ofread "5"? It can’t, because theres no way to resolve the result of the operation, sincereadis defined as(Read a) => String -> a.ais not dependent on the string, so it must use context.However usually context is something like
OrdorNumso its impossible to determine. This is not the monomorphism restriction but rather another case that can never be handled properly.Examples:
Does not Work:
Does Work:
These are necessary because the default
Showinstance, if I remember correctly, isInt.