我最近一直在学习 Haskell,我注意到 String
类型(或 [Char]
)可以订购。例如,这是有效的:
ghci> "foo" > "bar"
True
ghci> "?<>!" `compare` "[&*}"
LT
Haskell 如何下单
String
s,这个功能什么时候有用?
最佳答案
How does Haskell order Strings, and when would this functionality be useful?
首先,Char 是 Ord 的一个实例,由机器上底层原始 char 类型上的相等原语给出。
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
那么 String 被定义为
[Char]
(Char 列表),并且列表通常具有排序,如果它们的元素具有排序: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
就是这样。任何元素具有任何顺序的列表都将依次排序。
由于 Char 是按照其作为位模式的底层表示进行排序的,并且列表是按照列表的元素顺序给出的,因此您可以看到 String 的行为。
when would this functionality be useful?
用于将字符串插入多态的数据结构中,但需要排序方法。最著名的是Set和 Map .
关于string - Haskell 如何对字符串排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3126237/