Haskell IO monad并做表示法

时间:2013-04-05 12:02:11

标签: haskell io monads

以下Haskell snippit将无法编译,我无法弄清楚原因。

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

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

1 个答案:

答案 0 :(得分:12)

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

do
    action1
    action2

action1 >> action2

相同

由于>>的类型为Monad m => m a -> m b -> m baction1action2都应为monadic值。

您的compileProg函数看起来类型为TC -> String,而编译器期望某些TC -> IO aa,因为您在do中使用它符号

您可以使用let

do 
    let _ = compileProg tc
    return ()

让它编译。<​​/ p>

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

do
    putStrLn (compileProg tc)
    return ()

由于putStrLn的类型为String -> IO (),您可以删除return ()

do
    putStrLn (compileProg tc)

事实上,runCompiler可以简单地写成

runCompiler :: TC -> IO ()
runCompiler = putStrLn . compileProg
相关问题