simplesystems
simplesystems

Reputation: 849

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?

Example:

tail "a"
= ""

But you can create a String as:

'a' : []
= "a"

So I thought the tail should be the empty List [].

And if you do for example

tail ["x"]

then you get the empty List [].

This is a bit confusing.

Upvotes: 1

Views: 1573

Answers (3)

Yann Vernier
Yann Vernier

Reputation: 15887

It's because the empty String and empty list of Char are the exact same thing (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 instance for String; Show a => Show [a] handles all lists and uses 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.

Upvotes: 1

Alexey Romanov
Alexey Romanov

Reputation: 170805

Because the empty string is the empty list of Chars, it's just shown differently:

Prelude> [] :: String
""

Upvotes: 9

lsmor
lsmor

Reputation: 5063

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. So:

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

Regards,

Upvotes: 0

Related Questions