1

以下 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 () }

任何想法如何使它编译。我不明白为什么它不接受 () 作为给定的最终值。

4

1 回答 1

12

使用do符号排序两个语句时:

do
    action1
    action2

是相同的action1 >> action2

因为两者>>都有类型并且应该是一元值。Monad m => m a -> m b -> m baction1action2

看来您的compileProg函数具有 type TC -> String,而编译器希望它TC -> IO a适用于某些类型,a因为您以do符号形式使用它。

你可以使用一个let

do 
    let _ = compileProg tc
    return ()

让它编译。

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

do
    putStrLn (compileProg tc)
    return ()

因为putStrLn有类型String -> IO (),你可以删除return ()

do
    putStrLn (compileProg tc)

实际上runCompiler可以简单地写成

runCompiler :: TC -> IO ()
runCompiler = putStrLn . compileProg
于 2013-04-05T12:13:43.297 回答