Justin Ethier
Justin Ethier

Reputation: 134167

Haskell - Do literal backslashes always have to be escaped in a string?

In Haskell, in order to represent the literal string "\", one would normally write:

"\\"

However, is there a way to escape the string such that a single backslash can be written by itself without needing to be escaped? For example, I can do exactly this in C# by pre-pending @ to the string:

@"\"

Does Haskell have an equivalent?

Upvotes: 9

Views: 4630

Answers (3)

spinus
spinus

Reputation: 5765

There is a nice library (raw-strings-qq) which gives you QuasiQouter

import Text.RawString.QQ

multiline :: String
multiline = [r|<HTML>
<HEAD>
<TITLE>Auto-generated html formated source</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
</HEAD>
<BODY LINK="800080" BGCOLOR="#ffffff">
<P> </P>
<PRE>|]

Upvotes: 4

Emmanuel Touzery
Emmanuel Touzery

Reputation: 9173

It is possible using standard haskell, thanks to the QuasiQuoting mechanism:

http://www.haskell.org/haskellwiki/Poor_man%27s_here_document#Quasiquoting

That way, no \\ problem anymore. The only problem is that now you must be careful about the |] which terminates the quasiquoting sequence and that you may have to escape. In the context of regular expressions I escaped it myself using \u7c] or something like that, I don't remember exactly. So I used the unicode or ASCII code for the pipe character. But this |] sequence does not come up often.

And if you're interested in this to enter regular expressions, I'm a big fan of the Rex library:

http://hackage.haskell.org/package/rex

Which not only uses quasiquoting for nice regex entry (no double backslashes), it also uses perl-like regular expressions and not the default annoying POSIX regular expressions, and even allows you to use regular expressions as pattern matching your method parameters, which is genius.

Upvotes: 2

Nathan Shively-Sanders
Nathan Shively-Sanders

Reputation: 18389

No, see section 2.6 of Haskell Lexical Structure.

Haskell doesn't have raw strings, heredocs or triple strings. Sorry. The only fanciness you get is this:

  "ab\
  \cd"

=> 

"abcd"

White space between line-ending and -beginning slashes is ignored. This is useful, for example, if you want to emit some inline HTML that is properly indented in the Haskell source, but not overly indented in the output. (Not that I'd advocate doing complicated HTML output this way.)

Upvotes: 5

Related Questions