不敏感地排序字符串列表

时间:2014-10-13 15:19:57

标签: string sorting haskell quicksort

我试图在Haskell中不敏感地对字符串列表进行排序,但我得到了神秘的错误消息。这是我的代码:

import Data.Ord
import Data.List
import Data.Char (toUpper)


sortme :: (Ord a) => [a] -> [a]
sortme n = quickSort insensitively n

insensitively :: (Ord a) => a -> a -> Ordering
insensitively string1 string2 = compare (map toUpper string1) (map toUpper string2)


quickSort :: (Ord a) => (a -> a -> Ordering) -> [a] -> [a]
quickSort _ [] = []
quickSort c (x : xs) = (quickSort c less) ++ (x : equal) ++ (quickSort c more)
    where
        less  = filter (\y -> y `c` x == LT) xs
        equal = filter (\y -> y `c` x == EQ) xs
        more  = filter (\y -> y `c` x == GT) xs

quickSort接受一个排序函数和一个字符串列表,并通过排序函数对字符串进行排序。不敏感的是排序功能。这是我的错误信息:

/tmp/haskell114913-7-1rjcqe8/Sort.hs:11:54:
    Could not deduce (a ~ [Char])
    from the context (Ord a)
      bound by the type signature for
                 insensitively :: Ord a => a -> a -> Ordering
      at /tmp/haskell114913-7-1rjcqe8/Sort.hs:10:18-49
      `a' is a rigid type variable bound by
          the type signature for insensitively :: Ord a => a -> a -> Ordering
          at /tmp/haskell114913-7-1rjcqe8/Sort.hs:10:18
    In the second argument of `map', namely `string1'
    In the first argument of `compare', namely `(map toUpper string1)'
    In the expression:
      compare (map toUpper string1) (map toUpper string2)

1 个答案:

答案 0 :(得分:8)

您的功能定义很好,您的类型签名是问题所在。如果要删除它将编译的类型签名。问题是您已经说过insensitivelysortme排序任何Ord a,但您使用了map toUpper,这意味着它只能对字符串进行排序。只需使签名更具体:

sortme :: [String] -> [String]
insensitively :: String -> String -> Ordering

所以你认为这个错误信息是神秘的,所以让我们分解它。错误信息确实是:

Could not deduce (a ~ [Char])
from the context (Ord a)
  bound by the type signature for
             insensitively :: Ord a => a -> a -> Ordering
  Sort.hs:10:18-49
  `a' is a rigid type variable bound by
      the type signature for insensitively :: Ord a => a -> a -> Ordering
      at Sort.hs:10:18
In the second argument of `map', namely `string1'
In the first argument of `compare', namely `(map toUpper string1)'
In the expression:
  compare (map toUpper string1) (map toUpper string2)

删除了一些文件名噪音。要看的第一部分是

  

无法从上下文(a ~ [Char])

中推断(Ord a)

~符号表示类型相等。编译器说的是你说签名中有Ord a => a,但定义说它必须是[Char],而不是{/ 1>}中的任何Ord a

  

insensitively :: Ord a => a -> a -> Ordering

的类型签名

这意味着您已说insensitively比较任意两个Ord a值,但函数定义仅在a[Char]时有效。其余的错误消息只是告诉您错误所在代码中的位置:

  

map的第二个参数中,即string1

     

compare的第一个参数中,即(map toUpper string1)

     

在表达式中:compare (map toUpper string1) (map toUpper string2)