按字典顺序对字符串列表进行排序而不考虑大小写-Haskell
十个小时以来,我一直在尝试对这个字符串列表进行排序。这十个小时主要用于充实解决方法,但命运是残酷的,经过所有这些努力,我的解决方法仍然需要我对字符串列表进行排序而不考虑大小写。
我希望此函数执行的操作的示例:
Input: ["In", "Thats", "pLAIN"]
Output: ["In", "pLAIN", "Thats"]
基本上我想对字符串进行排序,就好像它们都是小写一样,但保持输入的大小写
到目前为止我的代码:
--This function inserts the strings with capitals in them into the list of lower case only strings
--alphabetically
insertCapitals :: [String] -> [String] -> [String]
insertCapitals capitalList lowerList
--Base case
|capitalList == [] && lowerList == [] = []
--If the capital list is empty then append the rest of the lowerList
|capitalList == [] = (lowerListHead:insertCapitals capitalList tailedLowerList)
--If the lowerList is empty append the rest of the capitalList
|lowerList == [] = (capitalListHead:insertCapitals tailedCapitalList lowerList)
--If the current lowercase word is less than the current uppercase word then append the lowercase word
|compareResult == LT = (lowerListHead:insertCapitals capitalList tailedLowerList)
--If the current uppercase word is less than the current lowercase word then append the uppercase word
|compareResult == GT = (capitalListHead:insertCapitals tailedCapitalList lowerList)
此代码是我的解决方法尝试的一部分。它的工作原理是获取原始列表,将其分解为一个完全小写字符串的列表和一个剩余的任何字符串的列表(所有这些都将有大写)。我的代码的问题在于它要求小写字符串列表和所有其他字符串列表按字母顺序排列,而不考虑大小写。
基本上我的问题来了个完整的循环。
提前感谢您的任何帮助
回答
你可以这样做
sortBy (comparing (map toLower))
或等效地,更快更短
sortOn (map toLower)
它完全符合它所说的,“通过比较字符串的小写版本进行排序”。
请参阅此处的文档:https : //hackage.haskell.org/package/base-4.14.1.0/docs/Data-List.html#v : sortOn
- Note that `sortOn` will probably have better performance than `sortBy` for this, since it uses the [Schwartzian transform](https://en.wikipedia.org/wiki/Schwartzian_transform) to avoid re-evaluating `toLower` from scratch every time an element is compared with another. My testing on some sample data shows it's about 30% faster.