简体   繁体   English

Haskell:弦尾“ a”

[英]Haskell: Tail of a String “a”

Why is the tail of a String with only one letter the empty String and not the empty List? 为什么只有一个字母的字符串的尾部是空字符串而不是空List?

Example: 例:

tail "a"
= ""

But you can create a String as: 但是您可以将String创建为:

'a' : []
= "a"

So I thought the tail should be the empty List [] . 所以我认为尾巴应该是空的List []

And if you do for example 如果你这样做

tail ["x"]

then you get the empty List [] . 然后您得到空的List []

This is a bit confusing. 这有点令人困惑。

Because the empty string is the empty list of Char s, it's just show n differently: 因为空字符串 Char的空列表,所以只是以不同的方式show n:

Prelude> [] :: String
""

It's because the empty String and empty list of Char are the exact same thing ( type String = [Char] ). 这是因为空的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. CharShow实例考虑了这一点,并覆盖列表呈现(使用showList )以呈现为字符串。 This is why there's no Show instance for String ; 这就是为什么String没有Show实例的原因; Show a => Show [a] handles all lists and uses showList [Char] . Show a => Show [a]处理所有列表并使用showList [Char]

As an aside, text is a lot more complex than just a string of characters. 顺便说一句,文本比只是一串字符要复杂得多。 That approximation was chosen early on in C and Haskell, but other implementations like Data.Text may have better approaches. 这种近似是在C和Haskell的早期选择的,但是其他实现如Data.Text可能有更好的方法。

When you define an instance of the Show type class you can implement the method showList, which is the way list of that type are display. 定义Show type类的实例时,可以实现showList方法,该方法是该类型的列表的显示方式。 So: 所以:

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

Regards, 问候,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM