gpt4 book ai didi

haskell - Haskell 中转义的 & 符号是什么意思?

转载 作者:行者123 更新时间:2023-12-02 09:51:21 29 4
gpt4 key购买 nike

我查看了Haskell 2010报告并注意到一个带有&符号的奇怪转义序列:\& 。我找不到这个转义序列应该代表什么的解释。它也可能只位于字符串中。我试过print "\&"在 GHCi 中,它会打印一个空字符串。

最佳答案

它逃脱了......没有字符。 “破坏”一些转义序列很有用。例如我们可能希望将 "\12"++ "3" 表示为单个字符串文字。如果我们尝试明显的方法,我们会得到

"\123" ==> "{"

但是我们可以使用

"\12\&3"

达到预期的结果。

此外,"\SOH""\SO" 都是有效的单个 ASCII 字符转义,使得 "\SO"++ "H" 很难表达为单个文字:我们需要 "\SO\&H"

标准 Show String 实例也利用了这种转义技巧,该实例必须生成有效的文字语法。我们可以在 GHCi 中看到这一点:

> "\140" ++ "0"
"\140\&0"
> "\SO" ++ "H"
"\SO\&H"

此外,这对旨在生成 Haskell 代码(例如用于元编程)的外部程序有很大帮助。当发出字符串文字的字符时,外部程序可以在可能不明确的转义符(甚至所有转义符)的末尾添加 \& ,以便程序不必处理不需要的交互。例如。如果程序现在想要发出 \12 ,它可以发出 \12\& 并且可以自由地发出任何内容作为下一个字符。否则,程序应该记住,当发出下一个字符时,如果它是数字,则必须在其前面添加 \& 。即使不需要,始终添加 \& 也更简单:\12\&A 是合法的,并且与 \12A 具有相同的含义.

最后,引用 Haskell 报告中的内容,解释 \&:

2.6 Character and String Literals

[...]

Consistent with the "maximal munch" rule, numeric escape characters in strings consist of all consecutive digits and may be of arbitrary length. Similarly, the one ambiguous ASCII escape code, "\SOH", is parsed as a string of length 1. The escape character \& is provided as a "null character" to allow strings such as "\137\&9" and "\SO\&H" to be constructed (both of length two). Thus "\&" is equivalent to "" and the character '\&' is disallowed. Further equivalences of characters are defined in Section 6.1.2.

关于haskell - Haskell 中转义的 & 符号是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56961342/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com