繁体   English   中英

Haskell IO monad和表示法

[英]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所以action1action2都应为单子值。

看来你的compileProg功能具有类型TC -> String ,而编译器期望它是TC -> IO a对一些a ,因为你正在使用它do记号。

您可以使用let

do 
    let _ = compileProg tc
    return ()

进行编译。

如果要输出返回的字符串,可以使用putStrLnprint

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM