[Haskell-cafe] String rewriting

Daniel Fischer daniel.is.fischer at web.de
Thu May 20 10:34:25 EDT 2010


On Thursday 20 May 2010 15:49:59, Roly Perera wrote:
> Hi,
>
> I'm looking for a simple way to rewrite strings according to simple
> composable rules like:
>
> replace "_" by "\\(\\hole\\)"
> replace "-n" where n matches an integer by "^{n}"
>
> so that I can import some pretty-printed output into a LaTeX alltt
> environment. I'm guessing that this nice functional stream
> transformation problem has been solved thousands of times. Could
> anyone point me to a simple package that would do this for me?
>
> many thanks,
> Roly

Hmm, I'm a little surprised that the Regex libraries don't seem to provide 
replacing functions (at least my short search didn't find any).

Still, shouldn't be too hard to use one of their matching functions to 
write a replacing function.

Or start from scratch:

repFun :: (String -> Maybe (String, String)) -> (String -> String)
                   -> String -> String
repFun test repl str@(c:cs)
    = case test str of
        Nothing -> c : repFun test repl cs
        Just (match, rest) -> repl match ++ repFun test repl rest
repFun _ _ [] = []

-- uses:

repFun uscore (const "\\(\\hole\\)")
    where
        uscore ('_':rest) = Just ("_",rest)
        uscore _ = Nothing

repFun dashDigs expo
    where
        dashDigs ('-':rest@(d:_))
            | isDigit d = Just (span isDigit rest)
        dashDigs _ = Nothing
        expo digs = '^':'{':digs ++ "}"


More information about the Haskell-Cafe mailing list