26

Haskell 98 specification says that the entry point of a program, namely, function main, should reside in the module called Main, by convention. However, even if you don't write module Main where at the top of the file you write main in, the source code compiles and seems working correct when you're using GHC.

The question is:

  1. What's the difference between writing module Main where and not writing it?
  2. Which one is preferred?
Pteromys
  • 1,441
  • 2
  • 12
  • 29

1 Answers1

24

There isn't really a difference, module Main (main) where would be the implicit definition when you don't specify a header yourself. From the Haskell 98 Report:

An abbreviated form of module, consisting only of the module body, is permitted. If this is used, the header is assumed to be module Main(main) where.

I would prefer an explicit definition to an implicit one but, for a Main.hs it's a minor preference.

James Brock
  • 3,236
  • 1
  • 28
  • 33
jdeseno
  • 7,753
  • 1
  • 36
  • 34
  • 9
    The difference is that without module header, only `main` is exported, but with `module Main where` every top-level definition is exported. Seems your eyes saw `module Main(main) where` where no export list was present ;) – Daniel Fischer Jun 20 '12 at 06:42
  • 5
    It is important to have the export list `(main)`, because that allows the compiler to optimize more. – augustss Jun 20 '12 at 08:43
  • @DanielFischer @augustss I can't find any documentation to support that. GHC doesn't seem to make that distinction when building an executable; it seems to do the same optimization and linking for `module Main(main) where` as `module Main where` as well. – jdeseno Jun 20 '12 at 14:39
  • 4
    Regarding the export behaviour, cf. http://www.haskell.org/onlinereport/haskell2010/haskellch5.html#x11-1000005.2 and the paragraph immediately before. Regarding optimisation, if only `main` is exported, the compiler can eliminate all other definitions by inlining if that seems good. If the other definitions in `Main` are exported too, the symbols for them must be generated in the object file. The compiler _may_ still optimise `main` the same as if only `main` were exported, but it may also do less inlining, because that would duplicate too much code. – Daniel Fischer Jun 20 '12 at 15:28
  • 2
    @DanielFischer Thanks. A little poking with `ghc --show-iface` and it all makes sense. – jdeseno Jun 20 '12 at 16:22