主要功能抱怨返回非IO monad [英] Main function complains of returning a non IO monad

查看:84
本文介绍了主要功能抱怨返回非IO monad的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import Debug.Trace

main = do
  trace "Main function parses, and returns - " "0"
  return ()

这将引发错误,

app.hs:3:1:
    Couldn't match expected type ‘IO t0’ with actual type ‘[()]’
    In the expression: main
    When checking the type of the IO action ‘main’

如果我没记错,该模块必须正常工作而不能返回.但是,无论有没有返回功能,它都无法正常工作.

If i am not wrong, the module must work without return. But with or without return function, it is not working.

推荐答案

trace不是IO操作!其类型为:

trace isn't an IO action! Its type is:

trace :: String -> a -> a

因此编译器会推断出您正在将main定义为在 List monad 中!因此,它抱怨您在应为IO ()时将其定义为[()].

so the compiler infers that you're defining main to be in the List monad! Hence it complains that you're defining it as a [()] when it should be IO ().

尝试改用traceIO(或简称为putStrLn).请记住,trace是调试功能:它不安全地打印内容,并从IO monad中爆发",这是一个真正有效的程序永远都不应做的事情.

Try using traceIO (or simply putStrLn) instead. Keep in mind that trace is a debugging function: it prints things unsafely and "breaks out" of the IO monad, which a real, working program should never ever do.

(通常,您可以通过自己编写类型签名来避免混淆:始终将main函数写为

(In general, you can avoid confusion by writing the type signatures yourself: always write your main function as

main :: IO ()
main = do
  ...

然后您得到的错误将不那么令人困惑,因为GHC不会推断出奇怪的类型.)

and then the error you get will be less confusing, as GHC won't infer a weird type.)

这篇关于主要功能抱怨返回非IO monad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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