When trying to load the following code into ghci:
import Control.Monad.Writer
newtype Writer w a = Writer { runWriter :: (a, w) }
logNumber :: Int -> Writer [String] Int
logNumber x = Writer (x, ["Got number: " ++ show x])
multWithLog :: Writer [String] Int
multWithLog = do
a <- logNumber 3
b <- logNumber 5
return (a*b)
(it's from http://learnyouahaskell.com/for-a-few-monads-more)
I'm receiving this error:
writer1.hs:8:16: error:
Ambiguous occurrence `Writer'
It could refer to either `Control.Monad.Writer.Writer',
imported from `Control.Monad.Writer' at writer1.hs:1:1-27
(and originally defined in `Control.Monad.Trans.Writer.Lazy')
or `Main.Writer', defined at writer1.hs:3:1
Failed, modules loaded: none.
I have read through related questions on SO e.g. Ambiguous occurrence `Just' but I'm still struggling to see how to best apply this in my case. Beyond this specific problem it would be great if you could point to any conventions of how to avoid similar naming ambiguities.
Edit:
As @chi pointed out in the comments I can skip newtype Writer w a = Writer { runWriter :: (a, w) }
and then use a provided function writer
instead of the Writer
constructor. However this differs from the code in the book (which uses Writer
) and when I call this in the REPL it shows me a different type WriterT
:
*Main> logNumber 3
WriterT (Identity (3,["Got number: 3"]))
So I'm still not sure if using the writer
function is how that code example is supposed to work.