以获得Escaped报价

以获得Escaped报价

本文介绍了模式匹配“字符串”以获得Escaped报价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下是我(错误地)尝试过的内容:

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

但结果不符合我所需的函数行为。

  ghci> g\ 
False
ghci>克 \\\


解决方案

字符串与字符串字符串有区别。基本上,一个字符串是一个接一个的字符列表,而字符串字面值只是一些标记的对于相同的。记号有逃脱的某些字符,因为否则它将导致模棱两可的语法,但它仍然表示字符串的的转义。



对于包含单个字符<$的字符串,Haskell表达式\符号 c $ c>。我们需要反斜杠,因为写了,而不会使字符串的内容看起来像是一个结束语并打破我们的记号。但字符串本身仍然只有一个



当您匹配字符串值时,重新匹配字符串本身,而不是它的符号,这意味着你不必担心字符串中的转义字符,因为它们只存在于符号级别,所以要匹配包含 您可以使用以下模式:

  foo [''] = ... 

如果您试图计算反斜杠,您将匹配不同的字符串。


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
解决方案

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.

这篇关于模式匹配“字符串”以获得Escaped报价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:39