[Haskell-beginners] Converting a function to -> Writer w a

David McBride toad3k at gmail.com
Wed Mar 6 22:51:19 CET 2013


It is a little bit roundabout, but here's how you would do a direct
translation:

import Control.Monad.Writer
import Data.Char ( toLower )
import Text.Regex.Posix ( (=~) )

replaceStuff :: String -> Writer [String] String
replaceStuff "" = return ""
replaceStuff cs = do
  let (pre, found, post) = cs =~ pattern
  tell ["found:" ++ found]
  moreStuff <- replaceStuff post
  return $ pre ++ transf found ++ moreStuff
     where pattern = "[A-E]" -- some regExp pattern
           transf   = map toLower -- placeholder function

main = print $ runWriter $ replaceStuff "this is thE Story of peter"

Other than running runWriter, just remember everything that was pure now
must be a monad, so return everything.  Also when you recurse that is also
now monadic.  It now prints instead of putStrLn because it must return a
tuple.  Everything else is pretty much the same.

On Wed, Mar 6, 2013 at 4:22 PM, Franco <franco00 at gmx.com> wrote:

> I am trying to get comfortble with the various monads, just to hone my
> tools
> for a better tomorrow.
>
> > import Control.Monad.Writer
>
> > import Data.Char ( toLower )
> > import Text.Regex.Posix ( (=~) )
>
> So I decided to code a very small example to 'get into it'. The following
> code is extremely simple. Given a string, it will find all occourences of
> a specific regexp, replace them, and return the changed string back.
>
> > replaceStuff :: String -> String
> > replaceStuff "" = ""
> > replaceStuff cs = let (pre, found, post) = cs =~ pattern in
> >                  pre ++ transf found ++ replaceStuff post
> >     where pattern = "[A-E]" -- some regExp pattern
> >           transf   = map toLower -- placeholder function
>
> > main :: IO ()
> > main = putStrLn $ replaceStuff "this is thE Story of peter"
>
> Yay, it works! Now let's talk about the Writer monad. I would like to have
> a mini log via the writer monad (could be anything , probably "x found and
> replaced with y")
>
> > type Log = String
>
> But after that I have no idea how to add the writer monad to my simple
> but recursive function. Type sig will be something like
>
>     replaceCols :: String -> Writer Log String
>
> but I don't know how to replace this part of the non monadic code
>
>      pre ++ transf found ++ replaceStuff post
>
> I wrote this before giving up
>
>      writer ((pre ++ found ++ ??whathere??),
>             (found ++ " found\n")) >>
>
> Probably I am no "getting it", so any help is appreciated! Thanks
>
> -F
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20130306/ed3aca9a/attachment.htm>


More information about the Beginners mailing list