Search code examples
haskellprogram-entry-pointconventionscompiler-flagstype-signature

Should one specify a type signature for main or not? Why / why not?


I learned from chapter 9 of Learn You A Haskell For Great Good that

By convention, we don't usually specify a type declaration for main.

As far as I can tell, this convention is widespread. However, if I compile, using the -Wall flag, a program that lacks a type signature for main, such as

-- test.hs

-- main :: IO ()
main = print (1 :: Int)

GHC does issue a warning:

$ ghc -Wall test.hs
[1 of 1] Compiling Main             ( test.hs, test.o )

test.hs:2:1: Warning:
    Top-level binding with no type signature: main :: IO ()
Linking test ...
$

I'm confused... If a type signature for main is indeed superfluous, why would -Wall cause GHC to complain when it's missing? Are there good reasons (aside from getting rid of that warning) for specifying main's type anyway?


Solution

  • Well, generally speaking, as that warning makes clear, it's always a good idea to give top-level bindings a type signature. In fact, it would be more reasonable to say

    By convention, we do specify a type declaration for everything1.

    Certainly, in a big project, main itself makes up a neglectable effort, so it really doesn't make any sense to omit the signature. Just write it out, for sake of consistency.

    However, though Haskell is great for properly structured projects and actually there's a tendency to write almost everything in libraries, it's also surprisingly good as a quick scripting language, for stuff other people would write in Python or Perl. And in those cases, you generally don't care that much about safety and good documentation etc., you just want to quickly write down something as concise as possible that does the job. You also normally don't compile those scripts with -Wall but just execute them with runhaskell. And as scripts always need to contain a main (unlike most other Haskell source files), it is indeed sensible enough to omit the signature here.

    I'd still suspect that the majority of Haskellers nowadays do write main::IO() even in the simplest scripts, if just out of habit.


    1Only everything on the top-level, that is. Local signatures sometimes do make sense as well, but often they rather clutter the code.