Haskell:字符串尾部 "a"

Haskell: Tail of a String "a"

为什么只有一个字母的字符串尾部是空字符串而不是空列表?

示例:

tail "a"
= ""

但您可以创建一个字符串为:

'a' : []
= "a"

所以我认为尾部应该是空列表[]

如果你这样做,例如

tail ["x"]

然后你得到空列表[]

这有点令人困惑。

当您定义 Show 类型的实例时 class 您可以实现方法 showList,这是显示该类型列表的方式。所以:

showList [] = "" -- I guess this is not the actual implementation, but something similar

此致,

因为空字符串 Char 的空列表,它只是 shown 不同:

Prelude> [] :: String
""

这是因为 String 的空列表和 Char 的空列表是完全相同的东西(type String = [Char]). The Show instance for Char takes this into account and overrides the list rendering (using showList) to render as strings. This is why there's no Show String 的实例;Show a => Show [a] 处理所有列表并使用 showList [Char]

顺便说一句,文本比一串字符要复杂得多。该近似值很早就在 C 和 Haskell 中选择,但其他实现如 Data.Text 可能有更好的方法。