Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control.Monad.Writer not working in haskell

Tags:

haskell

monads

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.

like image 994
baron aron Avatar asked Feb 20 '23 01:02

baron aron


1 Answers

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.

like image 132
Daniel Fischer Avatar answered Mar 07 '23 01:03

Daniel Fischer