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

Franco franco00 at gmx.com
Wed Mar 6 22:22:09 CET 2013


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



More information about the Beginners mailing list