简体   繁体   English

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

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

Good afternoon,下午好,

I'm a newb to Haskell, and I'm trying to adapt a QuickSort algorithm I made to sort lists of 'Int' with a list of tuples, but I quite can't figure out how to bind the tail to 'a' to make it work as I need it to, or if it's possible to reuse the code at all.我是 Haskell 的新手,我正在尝试调整我制作的 QuickSort 算法,以使用元组列表对“Int”列表进行排序,但我完全不知道如何将尾部绑定到“a”让它按照我的需要工作,或者是否可以重用代码。 Here's what I've been using to sort lists of 'Int':这是我用来对“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

And here is what I've tried to do with it so I could sort lists of tuples (Int,[Int]).这是我试图用它做的,所以我可以对元组列表(Int,[Int])进行排序。 I want to sort the tuples by the first element of the tuple, so if I get a lista like [(2,[1]),(1,[]),(3,[2,1])] it returns this [(1,[]),(2,[1]), (3,[2,1])].我想按元组的第一个元素对元组进行排序,所以如果我得到一个类似 [(2,[1]),(1,[]),(3,[2,1])] 的列表,它会返回这个[(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

If I try to load this, I get the following error:如果我尝试加载它,我会收到以下错误:

 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)

Many thanks in advance for any insight you could give me.非常感谢您能给我的任何见解。

notice in the expresion [a | a <- ps, a < x]表达式中的通知[a | a <- ps, a < x] [a | a <- ps, a < x] . [a | a <- ps, a < x] a is a tuple whereas x is an Int . a是一个元组,而x是一个Int Hence a < x makes no sense.因此a < x没有意义。 Any case, because your quicksort works on Ord a , you can use it for ordering a list of tuples as well.无论如何,因为您的quicksort适用于Ord a ,您也可以使用它对元组列表进行排序。 Try it`!试试看`!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM