为什么是“Main.main”,“IO()”和“而不是“IO a”? [英] Why is the type of "Main.main", "IO ()" and not "IO a"?

查看:140
本文介绍了为什么是“Main.main”,“IO()”和“而不是“IO a”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Main.main 类型必须是 IO()而不是 IO字符串 IO Int IO whatever

  main :: IO([] Char) - 类型错误
main =(>>)((>> =)getLine putStrLn)getLine


解决方案

> IO a 作为产生 a 的一个 IO 计算,关于运行时用 a main 产生的问题。它可以放弃它。这需要一个函数,如

  void :: IO a  - > IO() - 通常在Control.Monad中定义

然后给我们$ / $>

  realMain :: IO()
realMain = void main

除了文档外,没有特别的问题。如果我问你一个 IO a 的值,那么我可能会选择用 a 。如果我要求 IO()的值,那么这个不确定性就会减少:我可以自己创建()的值只要我喜欢,我不需要你的,因此我只需要关心运行 IO 计算的副作用。



这更符合 main 的实际用法,所以为了更清晰的类型,Haskell运行时可能要求 main :: IO() code>。



这也会迫使 main 的创建者清楚地知道他们如何处理他们创造的返回值。如果我有一个 mainish :: IO a ,那么在将它交给运行时之前,我需要显式地 void




就像Sibi指出的那样,GHC实际上接受 main :: IO a 并默默地放弃 a ,所以这个点有点没有意义。请参阅Haskell报告的第5章


Why the type of Main.main has to be IO () and not IO String or IO Int or IO whatever?

main :: IO ([] Char) -- Type error
main = (>>) ((>>=) getLine putStrLn) getLine

解决方案

If you read IO a as "an IO computation which produces an a" then it begs the question as to what the runtime does with the a that main produces. It could just drop it. That would require a function like

void :: IO a -> IO ()   -- defined more generally in Control.Monad

and then give us

realMain :: IO ()
realMain = void main

There's no particular problem with this except documentation. If I ask you for a value of IO a then there remains some uncertainty about what I might choose to do with that a. If I ask for a value of IO () then that uncertainty is diminished: I can create values of () myself whenever I like, I don't need yours, therefore I must only care about the side effects of running that IO computation.

This better matches that actual usage of main so for greater type clarity the Haskell runtime might ask for main :: IO ().

This also forces the creator of main to be explicit about what they do with any "return values" they create. If I have a mainish :: IO a then I need to explicitly void it before handing it off to the runtime.


That all said, as Sibi points out, GHC actually accepts main :: IO a and silently discards the a, so the point is a bit moot. See the intro to Chapter 5 of the Haskell Report.

这篇关于为什么是“Main.main”,“IO()”和“而不是“IO a”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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