QuickSort 应用于 Haskell 中的元组列表 (Int,[Int])

QuickSort applied to a list of tuples (Int,[Int]) in Haskell

下午好,

我是 Haskell 的新手,我正在尝试调整我制作的 QuickSort 算法,以使用元组列表对 'Int' 的列表进行排序,但我完全不能弄清楚如何将尾巴绑定到 'a' 以使其按我需要的方式工作,或者是否可以完全重用代码。这是我一直用来对 'Int' 列表进行排序的内容:

quickSort :: Ord a => [a] -> [a]
quickSort [] = []  
quickSort (x:xs) =   
let smallSort  = quickSort [a | a <- xs, a < x]  
    biggerSort = quickSort [a | a <- xs, a > x]  
in  smallSort ++ [x] ++ biggerSort

这就是我尝试用它做的事情,这样我就可以对元组列表 (Int,[Int]) 进行排序。我想按元组的第一个元素对元组进行排序,所以如果我得到一个像 [(2,[1]),(1,[]),(3,[2,1])] 这样的列表 returns 这个 [(1,[]),(2,[1]), (3,[2,1])].

quickSortTuplas ((x,(ks)) : []) = [(x,(ks))]
quickSortTuplas ((x,(ks)):ps) =   
let smallSort  = quickSort [a | a <- ps, a < x]  
    biggerSort = quickSort [a | a <- ps, a > x]  
in  smallSort ++ [(x,(ks))] ++ biggerSort

如果我尝试加载它,我会收到以下错误:

 Occurs check: cannot construct the infinite type: a ~ (a, [a1])
* In the second argument of `(>)', namely `x'
  In the expression: a > x
  In a stmt of a list comprehension: a > x
* Relevant bindings include
    a :: (a, [a1]) (bound at reNuevoHaskell.hs:60:37)
    biggerSort :: [(a, [a1])] (bound at reNuevoHaskell.hs:60:9)
    ps :: [(a, [a1])] (bound at reNuevoHaskell.hs:58:27)
    ks :: [a1] (bound at reNuevoHaskell.hs:58:22)
    x :: a (bound at reNuevoHaskell.hs:58:19)
    quickSortTuplas :: [(a, [a1])] -> [(a, [a1])]
      (bound at reNuevoHaskell.hs:57:1)

非常感谢您给我的任何见解。

表达式中的注意事项 [a | a <- ps, a < x] a 是一个元组,而 x 是一个 Int。因此 a < x 没有意义。无论如何,因为您的 quicksort 适用于 Ord a,您也可以使用它来对元组列表进行排序。试一试`!

quickSort :: Ord a => [a] -> [a]
quickSort [] = []  
quickSort (x:xs) =   
  let smallSort  = quickSort [a | a <- xs, a < x]  
      biggerSort = quickSort [a | a <- xs, a > x]  
   in smallSort ++ [x] ++ biggerSort

main = print $ quickSort [(1,[2,3,4]) , (0, [4,5,6]), (2,[1,2,3])] -- This works fine