Haskell中的main函数是否总是以main = do开头吗? [英] Does the main-function in Haskell always start with main = do?
问题描述
在Java中,我们总是这样写:
In java we always write:
public static void main(String[] args){...}
当我们想开始编写程序时.
when we want to start writing a program.
我的问题是,对于IE的Haskell来说是否一样:我是否可以始终确保声明: main =做,当我想为Haskell编写程序代码时?
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?
例如:
main = do
putStrLn "What's your name?"
name <- getLine
putStrLn ("Hello " ++ name)
该程序将询问用户您叫什么名字?" 然后,用户输入将存储在名称变量内部,并且 程序终止之前,将显示"Hello" ++名称.
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.
推荐答案
简短答案:否,我们必须声明一个main =
,但不是一个do
.
Short answer: No, we have to declare a main =
, but not a do
.
main
必须是 IO monad 类型(因此IO a
),其中a
是任意的(因为它被忽略了),如此处:
The main
must be an IO monad type (so IO a
) where a
is arbitrary (since it is ignored), as is written here:
使用名称
main
很重要:main
被定义为Haskell程序的入口点(类似于C中的main
函数),并且必须具有IO
类型,通常为IO ()
.
The use of the name
main
is important:main
is defined to be the entry point of a Haskell program (similar to themain
function in C), and must have anIO
type, usuallyIO ()
.
但是您不需要do
表示法.实际上 do
是语法糖 一个>.您的main
实际上是:
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)
或更优雅:
main = putStrLn "What's your name?" >> getLine >>= putStrLn . ("Hello " ++)
所以在这里我们写了一个没有do
表示法的main
.有关 desugaring do
表示法的更多信息,请参见此处
So here we have written a main
without do
notation. For more about desugaring do
notation, see here.
这篇关于Haskell中的main函数是否总是以main = do开头吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!