What is a good reason to use a type signature for functions when the compiler can infer the types

后端 未结 4 632
梦谈多话
梦谈多话 2021-01-17 09:44

I am trying to code using \'good Haskell style\' and so am trying to follow typical coding standards I find around. Also, compiling with -Wall and -Werror as I am used to w

4条回答
  •  天命终不由人
    2021-01-17 10:08

    If you make a mistake in defining your function, the compiler might infer a type that isn't what you expected it to be. If you've declared the type you expect, the compiler will report the error in the function's definition.

    Without the declaration, the compiler has no way to know that its inferred type is "wrong", and it will instead end up reporting errors in the places where you try to call the function, which makes it less clear where the problem really lies.

    If the calling functions don't have type declarations either, then instead of reporting errors there, the compiler might just infer incorrect types for those too, causing problems in their callers. You'll end up getting an error message somewhere, but it may be quite far removed from the actual root of the problem.


    Also, you can declare a more specific type than what the compiler would infer. For example, if you write the function:

    foo n = n + 1
    

    The compiler will infer the type Num a => a -> a, which means it must compile generic code that can work with any Num instance. If you declare the type as Int -> Int, the compiler may be able to produce more efficient code that's specialized for integers only.


    Finally, type declarations serve as documentation. The compiler may be able to infer the types of complex expressions, but it's not so easy for a human reader. A type declaration provides the "big picture" that can help a programmer understand what the function does.

    Note that Haddock comments are attached to declarations, not definitions. Writing a type declaration is the first step toward providing additional documentation for a function using Haddock.

提交回复
热议问题