Haskell中的main函数是否总是以main = do开头吗? [英] Does the main-function in Haskell always start with main = do?

查看:152
本文介绍了Haskell中的main函数是否总是以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 the main function in C), and must have an IO type, usually IO ().

但是您不需要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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆