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 String
s, and when would this functionality be useful?
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.
instance Ord Char where
(C# c1) > (C# c2) = c1 `gtChar#` c2
(C# c1) >= (C# c2) = c1 `geChar#` c2
(C# c1) <= (C# c2) = c1 `leChar#` c2
(C# c1) < (C# c2) = c1 `ltChar#` c2
then String is defined as a [Char]
(list of Char), and lists in general have an ordering, if their elements have an ordering:
instance (Ord a) => Ord [a] where
compare [] [] = EQ
compare [] (_:_) = LT
compare (_:_) [] = GT
compare (x:xs) (y:ys) = case compare x y of
EQ -> compare xs ys
other -> other
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.
when would this functionality be useful?
For inserting Strings into data structures that are polymorphic, but require an Ordering method. The most notable are Set and Map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With