I’ve recently been learning Haskell, and I noticed that the String type (or [Char]) can be ordered. For example, this is valid:
ghci> "foo" > "bar"
True
ghci> "?<>!" `compare` "[&*}"
LT
How does Haskell order Strings, and when would this functionality be useful?
Firstly, Char is an instance of Ord, given by equality primitives on the underlying primitive char type on the machine.
then String is defined as a
[Char](list of Char), and lists in general have an ordering, if their elements have an ordering:and that’s it. Any list whose elements have any ordering will in turn by ordered.
Since Char is ordered by its underlying representation as a bit pattern, and lists are given by element-wise ordering of the lists, you thus see the behavior for String.
For inserting Strings into data structures that are polymorphic, but require an Ordering method. The most notable are Set and Map.