[英]Haskell IO monad and do notation
以下Haskell摘录无法编译,我不知道为什么。
runCompiler :: TC -> IO ()
runCompiler tc = let cp' = cp in
do
cp'
return ()
where
cp = compileProg tc
我从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 () }
任何想法如何使它编译。 我看不到为什么它不接受()作为给定的最终值。
当使用do
标记测序两种说法:
do
action1
action2
与action1 >> action2
相同
因为>>
类型为Monad m => ma -> mb -> mb
所以action1
和action2
都应为单子值。
看来你的compileProg
功能具有类型TC -> String
,而编译器期望它是TC -> IO a
对一些a
,因为你正在使用它do
记号。
您可以使用let
do
let _ = compileProg tc
return ()
进行编译。
如果要输出返回的字符串,可以使用putStrLn
或print
:
do
putStrLn (compileProg tc)
return ()
由于putStrLn
类型为putStrLn
String -> IO ()
,因此可以删除return ()
:
do
putStrLn (compileProg tc)
实际上, runCompiler
可以简单地写为
runCompiler :: TC -> IO ()
runCompiler = putStrLn . compileProg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.