Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape double quotes in Haskell?

Tags:

haskell

I know that to escape special characters in Haskell we can use \", so if I try to pass as parameter:

parseString :: String
parseString = "{\"coord\":[\"D\",\"7\"],\"result\":\"HIT\",\"prev\":{\"coord\":[\"A\",\"10\"],\"result\":null,\"prev\":null}}"

to the function

take 7 parseString

everything works fine, but I'm wondering is there are shorter way to produce the same result, without putting escape symbol \" everywhere (imagine big JSON)?

For example, Python has this:

>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
like image 652
Mantas Savaniakas Avatar asked Oct 04 '18 07:10

Mantas Savaniakas


1 Answers

You escape double quotes with a backslash (\" in a string), like:

"\"To be, or not to be\" - William Shakespeare"

The above can of course be rather cumbersome in case you need to write a lot of double quotes. Haskell enables quasiquotes a way that is used by many Haskell packages to develop "mini-languages" inside Haskell. Quasiquotes are to the best of my knowledge not specified in the Haskell report, so it is not really a "Haskell feature", but the most popular compiler (GHC) supports this. A package like raw-strings-qq [Hackage] allows you to make use of this feature to write raw strings, like this:

{-# LANGUAGE QuasiQuotes #-}

import Text.RawString.QQ(r)

quote = [r|"To be, or not to be" - William Shakespeare|]

this thus produces strings like:

Prelude Text.RawString.QQ> [r|"To be, or not to be" - William Shakespeare|]
"\"To be, or not to be\" - William Shakespeare"

QuasiQuotes are not only used to produce raw strings. In Yesod for example there are a few mini-languages to define HTML/CSS/JavaScript templates in Shakespearean languages (hamlet, lucius, cassius, julius). It is typically used if expressing something in "vanilla" Haskell would take a lot of work, whereas writing it in a specific language makes it easier.

like image 107
Willem Van Onsem Avatar answered Sep 20 '22 15:09

Willem Van Onsem