首页 > 解决方案 > 对卡片列表进行排序

问题描述

我有一个卡片数据类型:

data Card = Card Rank
   deriving (Ord)

我可以在一个数组中创建编号的卡片,表示为:

mycard = [Card 1,Card 7, Card 3]

我现在正在尝试根据卡片的排名按降序对卡片进行排序,特别是使用快速排序。因此我会得到

[Card 7, Card 3, Card 1]

我写:

quicksort :: [Card] -> [Card]  
quicksort [] = []  
quicksort (x:xs) =   
    let smallerSorted = quicksort [a | a <- xs, a <= x !! 1]  #compare at index 1 which is the rank
        biggerSorted = quicksort [a | a <- xs, a > x !! 1] #compare at index 1 which is the rank 
    in  smallerSorted ++ [x] ++ biggerSorted 

但我收到一个错误说

Couldn't match expected type ‘[Card]’ with actual type ‘Card’
• In the first argument of ‘(!!)’, namely ‘x’
  In the second argument of ‘(>)’, namely ‘x !! 1’
  In the expression: a > x !! 1

标签: haskell

解决方案


x是一张卡片,您正在尝试使用x !! 1. 的第一个参数!!必须是一个列表 ( [Card]),但是您提供了一个Card,因此出现了错误。

我认为您应该与 just 进行比较x


推荐阅读