Haskell - What makes 'main' unique?

你离开我真会死。 提交于 2019-12-01 03:59:57

Because the language spec says so.

A Haskell program is a collection of modules, one of which, by convention, must be called Main and must export the value main. The value of the program is the value of the identifier main in module Main, which must be a computation of type IO t for some type t (see Chapter 7). When the program is executed, the computation main is performed, and its result (of type t) is discarded.

As GolezTrol said, all programs need to know which symbol to start executing when the function is invoked. Many scripting languages don't require (or just don't need) a main routine as they can have statements placed on the top level. This is not the case for Haskell, C and many others - these languages need a starting location and by convention that is the main function (as per the Haskell spec - see Cat's answer).

Notice Haskell's main does not accept any parameters that correspond to the program arguments - these are obtained via System.Environment.getArgs.

As in C, Java, or C#, main is a special identifier in certain contexts that indicates where the program should start.

In Haskell, main is defined to have the type IO a. You should either give your function a different name, or if you really want it to be the starting point, change its signature and have it read the arguments from the command line with getArgs

Although you didn't ask it specifically, main is also special in that it is the only function in a Haskell program that can (safely) invoke IO actions. The Haskell runtime treats main as special.

By definition, main is a function that takes no arguments and returns a value of type IO a that is discarded by the runtime. What your error message is saying is that your main does not comply with these requirements. This is indeed true, as your main receives two parameters.

In order to access command line parameters, use System.Environment.getArgs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!