[Haskell-beginners] Re: Iterating through a list of char...
Stephen Tetley
stephen.tetley at gmail.com
Thu Apr 29 17:16:47 EDT 2010
On 29 April 2010 21:39, Jean-Nicolas Jolivet <jeannicolascocoa at gmail.com> wrote:
[Snip]
> Every solution I found was iterating to a list of character one character at
> a time, and outputting a character as a result (whether it is by recursion,
> mapping, etc..), however, what I was trying to explain in my previous post
> was that; when I am processing the escape character, this character should
> not be added to the resulting string... This is where I decided to use the
> Maybe monad..I'm just wondering if there is a better way...!
Hi Jean-Nicolas
The 'hand crafted lexer' style is quite common for this, with
different functions for different states (here body and escape).
I use a Hughes list as an explicit accumulator (a Hughes list is
sometimes called a difference list and familiar for strings as the
ShowS type synonym). This has more efficient right-addition (snoc)
than normal lists [a].
> toString :: ShowS -> String
> toString = ($ [])
> snoc :: ShowS -> Char -> ShowS
> snoc f a = f . (a:)
> emptyH :: ShowS
> emptyH = id
> escape :: String -> ShowS -> ShowS
> escape (_:xs) acc = body xs acc -- drop1, change state
> escape _ acc = acc -- oh dear escape to the end-of-string
> body :: String -> ShowS -> ShowS
> body ('\\':xs) acc = escape xs acc -- change state
> body (x:xs) acc = body xs (acc `snoc` x)
> body _ acc = acc
> run :: String -> String
> run xs = toString (body xs emptyH)
> demo1 = run "\\s1234" -- "1234"
Best wishes
Stephen
More information about the Beginners
mailing list