[Haskell-beginners] Question about example in 'using do notation with Writer' section of LYH
David McBride
toad3k at gmail.com
Thu Jan 26 16:02:44 UTC 2017
Nothing happens to them. They are still in there. Whereas logNumber
always returns the number you give it, multiWithLog always returns 15
and appends two strings into its state ("got number 3 and 5").
You can return whatever value you want from a Monad. In this case
he's doing a * b, but you could do 2 * b, Just (a + b) or anything
else. As an example, here I return a tuple instead.
multWithLogTuple :: Writer [String] (Int,Int,Int)
multWithLogTuple = do
a <- logNumber 3
b <- logNumber 5
return (a,b,2*b)
>runWriter multWithLogTuple
((3,5,10),["Got number: 3","Got number: 5"])
On Thu, Jan 26, 2017 at 10:41 AM, Olumide <50295 at web.de> wrote:
> Hello List,
>
> Chapter 14 of LYH ( http://learnyouahaskell.com/for-a-few-monads-more#reader
> ) has the following bit of code:
>
>
> import Control.Monad.Writer
>
> 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)
>
> I have a fair grasp of what's going bu the last line return(a*b) eludes me.
> Specifically its the a*b part that baffles me. I think 3 is bound to 'a' and
> 5 to 'b', then return(a*b) would put the value 15 in a context ... So what
> becomes of the string parts of the Writer monads created by logNumber 3 and
> logNumber 5 respectively.
>
> Regards,
>
> - Olumide
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
More information about the Beginners
mailing list