我正在尝试按每条记录中的第二个元素对记录序列进行排序。问题是这些不是一个值,而只是一个类型。我有一个函数,它根据它的类型返回值。
这就是我所拥有的:
type Suit = Spades | Clubs | Hearts | Diamonds
type Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King
type Card = { suit: Suit; rank: Rank}
type Hand = Card seq
let cardValue(card:Card) =
if (card.rank = Ace) then 1
elif (card.rank = Two) then 2
elif (card.rank = Three) then 3
elif (card.rank = Four) then 4
elif (card.rank = Five) then 5
elif (card.rank = Six) then 6
elif (card.rank = Seven) then 7
elif (card.rank = Eight) then 8
elif (card.rank = Nine) then 9
elif (card.rank = Ten) then 10
elif (card.rank = Jack) then 10
elif (card.rank = Queen) then 10
elif (card.rank = King) then 10
else 0
let sortHandByValue(hand:Hand) =
......missing code here......
我想要做的是将Rank作为一个值排序。
所以例如Hand是:{{Hearts;三}; {黑桃;插口}; {钻石;两个}}
它会对Hand进行排序,结果是:{{钻石;二}; {心;三}; {黑桃;千斤顶}}
我尝试过手|> Seq.sort |> Seq.groupBy id |> Seq.map snd但是它没有按值排序,只能按字母顺序排序。
我无法更改任何类型,但我可以更改其他所有类型。 任何想法都将不胜感激,谢谢!
答案 0 :(得分:1)
你需要清理代码,因为它显示记录,我重写了Card类型作为元组和匹配函数。然后您需要的是管道Seq.sortBy
或Seq.sortByDescending
(按升序排序):
type Suit = Spades | Clubs | Hearts | Diamonds
type Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King
type Card = Suit * Rank
type Hand = Card seq
let cardValue (card:Card) =
match card with
| _, Ace -> 1
| _, Two -> 2
| _, Three -> 3
| _, Four -> 4
| _, Five -> 5
| _, Six -> 6
| _, Seven -> 7
| _, Eight -> 8
| _, Nine -> 9
| _, Ten | _, Jack | _, Queen | _, King -> 10
let hand = seq [(Hearts, Three); (Spades, Jack); (Diamonds, Two)]
hand |> Seq.sortBy cardValue
//val it : seq<Suit * Rank> =
//seq [(Diamonds, Two); (Hearts, Three); (Spades, Jack)]
带记录的版本: 我把它保持在你的原件附近。
/// Version with Records
type Suit = Spades | Clubs | Hearts | Diamonds
type Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King
type Card = { suit: Suit; rank: Rank}
type Hand = seq<Card>
let cardValue(card:Card) =
if (card.rank = Ace) then 1
elif (card.rank = Two) then 2
elif (card.rank = Three) then 3
elif (card.rank = Four) then 4
elif (card.rank = Five) then 5
elif (card.rank = Six) then 6
elif (card.rank = Seven) then 7
elif (card.rank = Eight) then 8
elif (card.rank = Nine) then 9
elif (card.rank = Ten) then 10
elif (card.rank = Jack) then 10
elif (card.rank = Queen) then 10
elif (card.rank = King) then 10
else 0
let hand = seq [{suit=Hearts; rank=Three}; {suit=Spades;rank=Jack}; {suit=Diamonds;rank= Two}]
hand |> Seq.sortBy cardValue
val it:seq = seq [{suit = Diamonds; rank = Two;}; {suit = Hearts; rank = Three;}; {suit =黑桃; rank = Jack;}]