首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Haskell IO monad和do notation

Haskell IO monad和do notation
EN

Stack Overflow用户
提问于 2013-04-05 20:02:11
回答 1查看 322关注 0票数 1

下面的Haskell snippit不能编译,我不知道为什么。

代码语言:javascript
复制
runCompiler :: TC -> IO ()
runCompiler tc = let cp' = cp in 
    do 
        cp'
        return ()
    where
    cp = compileProg tc

我从GHCi得到以下错误:

代码语言:javascript
复制
    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 () }

你有什么办法让它编译吗?我不明白为什么它不接受()作为给定的最终值。

EN

回答 1

Stack Overflow用户

发布于 2013-04-05 20:13:43

使用do表示法对两个语句进行排序时:

代码语言:javascript
复制
do
    action1
    action2

action1 >> action2相同

因为>>的类型是Monad m => m a -> m b -> m b,所以action1action2都应该是一元值。

您的compileProg函数似乎具有类型TC -> String,而编译器希望它对于某些aTC -> IO a,因为您在do表示法中使用它。

您可以使用let

代码语言:javascript
复制
do 
    let _ = compileProg tc
    return ()

来编译它。

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

代码语言:javascript
复制
do
    putStrLn (compileProg tc)
    return ()

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

代码语言:javascript
复制
do
    putStrLn (compileProg tc)

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

代码语言:javascript
复制
runCompiler :: TC -> IO ()
runCompiler = putStrLn . compileProg
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15833459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档