[英]Haskell IO monad and do notation
The following Haskell snippit will not compile and I can't figure out why. 以下Haskell摘录无法编译,我不知道为什么。
runCompiler :: TC -> IO ()
runCompiler tc = let cp' = cp in
do
cp'
return ()
where
cp = compileProg tc
I am getting the following error from GHCi: 我从GHCi中收到以下错误:
Couldn't match expected type `IO a0' with actual type `String'
In a stmt of a 'do' block: cp'
In the expression:
do { cp';
return () }
In the expression:
let cp' = cp
in
do { cp';
return () }
Any ideas what to do to make it compile. 任何想法如何使它编译。 I can't see why it will not accept () as the final value given.
我看不到为什么它不接受()作为给定的最终值。
When using do
notation sequencing two statements: 当使用
do
标记测序两种说法:
do
action1
action2
is the same as action1 >> action2
与
action1 >> action2
相同
since >>
has type Monad m => ma -> mb -> mb
both action1
and action2
should be monadic values. 因为
>>
类型为Monad m => ma -> mb -> mb
所以action1
和action2
都应为单子值。
It appears your compileProg
function has type TC -> String
, while the compiler expects it to be TC -> IO a
for some a
since you are using it in do
notation. 看来你的
compileProg
功能具有类型TC -> String
,而编译器期望它是TC -> IO a
对一些a
,因为你正在使用它do
记号。
You can use a let
您可以使用
let
do
let _ = compileProg tc
return ()
to get it to compile. 进行编译。
If you want to output the returned string, you can use putStrLn
or print
: 如果要输出返回的字符串,可以使用
putStrLn
或print
:
do
putStrLn (compileProg tc)
return ()
since putStrLn
has type String -> IO ()
you can remove the return ()
: 由于
putStrLn
类型为putStrLn
String -> IO ()
,因此可以删除return ()
:
do
putStrLn (compileProg tc)
In fact runCompiler
can be written simply as 实际上,
runCompiler
可以简单地写为
runCompiler :: TC -> IO ()
runCompiler = putStrLn . compileProg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.