Control.Monad.Writer not working in haskell

2019-06-28 06:36发布

问题:

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.

回答1:

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.