Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't a String an Enum?

Tags:

haskell

Why is [Char] an instance of Ord, but not of Enum?

Prelude> let succ_a = "a" ++ [minBound::Char]
Prelude> "a" < succ_a
True
Prelude> succ_a < "a "
True
Prelude> succ_a < succ_a ++ [minBound::Char]
True

I think there's no String between "a" and succ_a - so why not succ "a" == succ_a?

like image 569
gcbenison Avatar asked Nov 29 '22 02:11

gcbenison


1 Answers

Since strings are lists in Haskell, you might as well ask why lists aren't in Enum, since you wouldn't be able to write an instance for just strings without extensions. But that doesn't matter. The problem is that enumeration in lexicographical order isn't very useful, since you just keep appending the smallest character at the end indefinitely.

Using the alphabet a..z for simplicity, lexicographical order just gives us repetitions of the first letter.

"", "a", "aa", "aaa", "aaaa", "aaaaa" ...

The more useful order for enumerating strings is by length. This way, we first get the empty string, then all the strings of length 1, then all of length 2, etc.

"", "a", "b", ... "z", "aa", "ba", ... "za", "ab", ... "zz", "aaa", "baa" ...

This is essentially the same as enumerating integers, with the digits reversed, so when you get to "zz" you carry and get "aaa", just like how you get from 99 to 100.

However, this would be inconsistent with the Ord instance for lists which uses the lexicographical ordering.

like image 67
hammar Avatar answered Dec 08 '22 09:12

hammar