Kevin Meredith
Kevin Meredith

Reputation: 41909

Pattern Matching on 'String' to get Escaped Quote

Is it possible to pattern match on an escaped quote?

Here's what I (incorrectly) tried:

g :: String -> Bool
g ('\\':'"':_) = True
g _            = False

But the results don't meet my desired function behavior.

ghci> g "\""
False
ghci> g "\\\""
True

Upvotes: 1

Views: 315

Answers (1)

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

There's a difference between a string and a string literal. Basically, a string is a list of characters one after the other and a string literal is just some notation for the same. The notation has to "escape" certain characters because it would otherwise lead to ambiguous syntax, but it still expresses the string without the escaping.

The Haskell expression "\"" is notation for the string containing a single character ". We need the backslash because writing """ without it would make the contents of the string look just like a closing quote and break our notation. But the string itself still only has a ".

When you're matching on a string value, you're matching on the string itself, not its notation. This means that you do not have to worry about escape characters in the string, because those only exist at the level of notation. So to match the string containing just " you would use the following pattern:

foo ['"'] = ...

If you tried to account for a backslash, you would be matching a different string.

Upvotes: 5

Related Questions