Search code examples
haskellprogram-entry-pointdo-notation

Does the main-function in Haskell always start with main = do?


In java we always write:

public static void main(String[] args){...}

when we want to start writing a program.

My question is, is it the same for Haskell, IE: can I always be sure to declare: main = do, when I want to write code for a program in Haskell?

for example:

main = do  
    putStrLn "What's your name?"  
    name <- getLine 
    putStrLn ("Hello " ++ name) 

This program is going to ask the user "What's your name?" the user input will then be stored inside of the name-variable, and "Hello" ++ name will be displayed before the program terminates.


Solution

  • Short answer: No, we have to declare a main =, but not a do.

    The main must be an IO monad type (so IO a) where a is arbitrary (since it is ignored), as is written here:

    The use of the name main is important: main is defined to be the entry point of a Haskell program (similar to the main function in C), and must have an IO type, usually IO ().

    But you do not necessary need do notation. Actually do is syntactical sugar. Your main is in fact:

    main =
        putStrLn "What's your name?" >> getLine >>= \n -> putStrLn ("Hello " ++ n)
    

    Or more elegantly:

    main = putStrLn "What's your name?" >> getLine >>= putStrLn . ("Hello " ++)
    

    So here we have written a main without do notation. For more about desugaring do notation, see here.