Haskell如何命令字符串?

Ben*_*Ben 4 sorting string haskell

我最近一直在学习Haskell,我注意到可以订购String类型(或[Char]).例如,这是有效的:

ghci> "foo" > "bar"
True
ghci> "?<>!" `compare` "[&*}"
LT
Run Code Online (Sandbox Code Playgroud)

Haskell如何排序String,以及此功能何时有用?

Don*_*art 9

Haskell如何命令字符串,以及此功能何时有用?

首先,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
Run Code Online (Sandbox Code Playgroud)

然后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
Run Code Online (Sandbox Code Playgroud)

就是这样.其元素具有任何排序的任何列表将依次按顺序排列.

由于Char按其基础表示形式排序为位模式,并且列表是按列表的元素顺序排列的,因此您可以看到String的行为.

这个功能何时有用?

用于将字符串插入到多态的数据结构中,但需要使用Ordering方法.最值得注意的是SetMap.


por*_*ges 7

Haskell如何命令字符串,

以下是Haskell Prelude的一些定义.

字符串只是字符列表:

type String = [Char]
Run Code Online (Sandbox Code Playgroud)

字符按Unicode代码点排序:

instance  Ord Char  where
    c <= c' = fromEnum c <= fromEnum c'
Run Code Online (Sandbox Code Playgroud)

列表使用词典顺序进行比较(隐式地通过列表的结构和自动派生的定义Ord):

data [a] = [] | a : [a] deriving Ord -- not actually valid Haskell :)

instance Ord a => Ord [a]
Run Code Online (Sandbox Code Playgroud)

这个功能何时有用?

你需要一个Ord使用像Map或的东西的实例Set.