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

后端 未结 2 1036
萌比男神i
萌比男神i 2021-01-12 19:30

In java we always write:

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

when we want to start writing a program.

My question i

2条回答
  •  攒了一身酷
    2021-01-12 20:00

    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.

提交回复
热议问题