是否可以在转义报价上进行模式匹配?
这是我(错误地)尝试的:
g :: String -> Bool g ('\\':'"':_) = True g _ = False但结果不符合我期望的功能行为。
ghci> g "\"" False ghci> g "\\\"" TrueIs it possible to pattern match on an escaped quote?
Here's what I (incorrectly) tried:
g :: String -> Bool g ('\\':'"':_) = True g _ = FalseBut the results don't meet my desired function behavior.
ghci> g "\"" False ghci> g "\\\"" True最满意答案
字符串和字符串之间有区别。 基本上,一个字符串是一个接一个的字符列表,字符串文字只是一些符号 。 该符号必须“逃避”某些字符,否则会导致模糊的语法,但它仍然表示没有转义的字符串。
Haskell表达式"\""是包含单个字符的字符串的表示法 " 。 我们需要反斜杠,因为在没有它的情况下编写"""会使字符串的内容看起来就像一个结束引号并打破我们的符号。但字符串本身仍然只有一个" 。
当您匹配字符串值时,您将匹配字符串本身,而不是其符号。 这意味着您不必担心字符串中的转义字符,因为它们只存在于符号级别。 所以要匹配只包含"你会使用以下模式的字符串:
foo ['"'] = ...如果您尝试考虑反斜杠,则会匹配不同的字符串。
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.
更多推荐
发布评论