Control.Monad.Writer不能在haskell中工作 [英] Control.Monad.Writer not working in haskell

查看:161
本文介绍了Control.Monad.Writer不能在haskell中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图编译Haskell代码 - 再次涉及到Control.Monad.Writer。下面是一个代码示例,它不会从 学习你学习Haskell

  import Control.Monad.Writer 

gcd':: Int - > Int - > Writer [String] Int
gcd'a b
| b == 0 = do
tell [用++显示a结束
返回
|否则= do
tell [show a ++mod++ show b ++=++ show(a`mod` b)]
gcd'b(a`mod` b)

我收到此错误:

<$ p $
可能的修正:
添加一个实例声明,用于(显示(Writer [String] Int))
由于使用`print' Show(Writer [String] Int))
在一个交互式GHCi命令中:print it

我试过编写代码,我的老师今天写的也涉及到Control.Monad.Writer,但没有任何效果。

我使用的是Ubuntu 12.04,gedit和GHC 7.4。 1



来自的所有Writer monad程序学习你一个Haskell 未能编译,而且我坚持原样。

解决方案

C> ghci中>在ghci提示符下输入gcd'12345 6789

。因此,你要求ghci输出 Writer [String] Int 类型的值,但是显示实例用于 Writer 类型,因此ghci不能打印它。您需要申请 runWriter 或类似的功能,

  ghci> runWriter $ gcd'12345 6789 

应该可以工作。


I have been trying to compile Haskell code all day – again – involving Control.Monad.Writer. Here is a code example that won't compile from Learn You a Haskell:

import Control.Monad.Writer  

gcd' :: Int -> Int -> Writer [String] Int  
gcd' a b  
    | b == 0 = do  
        tell ["Finished with " ++ show a]  
        return a  
    | otherwise = do  
        tell [show a ++ " mod " ++ show b ++ " = " ++ show (a `mod` b)]  
        gcd' b (a `mod` b)

I receive this error:

No instance for (Show (Writer [String] Int))
      arising from a use of `print'
    Possible fix:
      add an instance declaration for (Show (Writer [String] Int))
    In a stmt of an interactive GHCi command: print it

I have tried compiling code my teacher wrote today also involving Control.Monad.Writer but nothing works.

I am using Ubuntu 12.04, gedit, and GHC 7.4.1.

All the Writer monad programs from Learn You a Haskell have failed to compile, and I am pretty stuck as it is.

解决方案

You apparently entered something like

ghci> gcd' 12345 6789

at the ghci prompt. Thus you asked ghci to print a value of type Writer [String] Int, but there's no Show instance for Writer types, hence ghci can't print it. You need to apply runWriter or a similar function,

ghci> runWriter $ gcd' 12345 6789

should work.

这篇关于Control.Monad.Writer不能在haskell中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆