简体   繁体   中英

Function pattern matching in Haskell

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?

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 :

  • To tell the compiler what you actually mean. In case you make a mistake writing the function, the compiler will not infer a bad type, but warn you of your mistake
  • To tell the people who read your code. They'll have to find out the type of the function anyway while understanding the code, so you might as well make it easier for them. Having the type explicitly makes the code more readable.

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.

For documentation purpose, and because for some type extensions the automatic inference fails. Read here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM