不敏感地排序字符串列表

Has*_*ier 2 sorting string 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
Run Code Online (Sandbox Code Playgroud)

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

bhe*_*ilr 8

您的函数定义很好,您的类型签名是问题.如果要删除它将编译的类型签名.问题是你已经说过insensitively并对它进行sortme排序Ord a,但你已经习惯了map toUpper,这意味着它只能对字符串进行排序.只需使签名更具体:

sortme :: [String] -> [String]
insensitively :: String -> String -> Ordering
Run Code Online (Sandbox Code Playgroud)

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

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

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

无法(a ~ [Char])从上下文中推断出来(Ord a)

~符号装置类型的平等.什么编译器说是你说的签名将Ord a => a在里面,但定义说,它必须是[Char],不是任何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)