Reputation: 585
I'm trying to learn Haskell in guidance of Learn You a Haskell, but the following puzzles me.
lucky :: (Integral a) => a -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry, you're out of luck, pal!"
As you can see, there's one line up there stating the exact types of the function. But is this necessary? Can't the types of parameters and return values be deduced from the patterns below that line?
Upvotes: 0
Views: 244
Reputation: 12961
You are right, they are absolutely not necessary. However, it's a very common practice to state the type of the function nevertheless, for at least two reasons :
This is why, although they are optional, the types of top level functions are almost always spelled out in Haskell code.
To complete with what Zeta said, it is not necessary in this case. However, in some situations, it is necessary to specify the type of the function when the code is too ambiguous to infer.
Upvotes: 6
Reputation: 1321
For documentation purpose, and because for some type extensions the automatic inference fails. Read here.
Upvotes: -2