# Parsing strings with escaped characters using Parsec

I have been working through the exercises in a Write Yourself a Scheme in 48 Hours/Parsing and hacked together something to get parseString to comprehend escaped characters. Also had some inspiration from Real World Haskell chapter 16 minus the applicative parts.

parseString :: Parser LispVal
parseString = do char '"'
x <- many $chars char '"' return$ String x
where chars = escaped <|> noneOf "\""
escaped = choice $map tryEscaped escapedChars tryEscaped c = try$ char '\\' >> char (fst c) >> return (snd c)
escapedChars = zip "bnfrt\\\"/" "\b\n\f\r\t\\\"/"


This works but I am not fond of my 'tryEscaped' definition. What are the alternatives?

• Is \/ really a valid escape sequence in scheme? – sepp2k May 14 '11 at 14:31

Some suggestions:

• Replace fst and snd with a pattern match or explicit function arguments.
• Extract the common char '\\' parser. You can then avoid the try.
• Strings with lots of escaped characters are hard to read and it's hard to visually verify that the escape codes are correctly matched with their replacements. Consider spelling them out and aligning them to make this easy to see.

Here's what I came up with:

escaped = char '\\' >> choice (zipWith escapedChar codes replacements)
escapedChar code replacement = char code >> return replacement
codes        = ['b',  'n',  'f',  'r',  't',  '\\', '\"', '/']
replacements = ['\b', '\n', '\f', '\r', '\t', '\\', '\"', '/']

• Hey, please note in 7.10 you will get an error message suggesting you enable FlexibleContext. This is due to not having an explicit type signature on the function escapedChar. The proper fix, IMO, is to give it an explicit type signature: escapedChar :: Char -> Char -> Parser Char or you may be able to utilize an anonymous function to the same effect. – Alex Hart Sep 8 '15 at 14:21

The OP is doing this as exercise, but for anyone who found this question on google like I did and wants a fast solution: import Parsec's Token and Language.

Then you can do this in GHCi:

>>>let lexer = makeTokenParser haskellDef
>>>let p = stringLiteral lexer
>>>runParser p () "" "\"Hi\\n\""
Right "Hi\n"


According to the Parsec docs:

the literal string is parsed according to the grammar rules defined in the Haskell report (which matches most programming languages quite closely)

• I was looking for an out of the box solution. This works great! – Damian Nadales Nov 9 '17 at 13:34
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 1, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.3407856822013855, "perplexity": 6886.023188854603}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 20, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2020-16/segments/1585370493818.32/warc/CC-MAIN-20200329045008-20200329075008-00494.warc.gz"}