F#类型和循环 [英] F# Types and Looping
问题描述
我正在研究F#教程,该教程创建了一副纸牌.列出了这些类型,但是我不明白如何遍历这些类型来创建整个甲板的地图.我希望做类似
I am working on an F# tutorial that creates a deck of cards. The types are listed, but I cannot understand how to loop through the types to create the map of the full deck. I expected to do something like
Foreach rank in ranks
Foreach suit in suits
somehow combine the two
next suit
next rank
有没有办法做到这一点?下面是创建的类型.
Is there no way to do this? Below are the types created.
我想如果我将它们从类型更改为列表,它们可以合并,对吗?那么,类型有什么意义呢?
I think if I changed them from types to lists they could union, right? So, what's the point of types?
type suits=
|Spade=1
|Heart=2
|Club=3
|Diamond=4
type ranks=
|ValCard of int
|Jack
|Queen
|King
type deck= Deck of ranks * suits
推荐答案
枚举是代表卡片的好选择.您可以免费在西装之间和等级之间进行比较,并轻松将枚举从/转换为int
.
Enums is a good choice for representing cards. You have comparison among suits and among ranks for free, and easily convert enums from/to int
.
type suit =
| Spade = 1
| Heart = 2
| Club = 3
| Diamond = 4
type rank =
| Ace = 1 | Two = 2 | Three = 3 | Four = 4 | Five = 5 | Six = 6 | Seven = 7
| Eight = 8 | Nine = 9 | Ten = 10 | Jack = 11 | Queen = 12 | King = 13
/// 'Card' is a type which represents a particular card
type Card = Card of rank * suit
/// 'deck' is a list consisting of all cards in a full deck
let deck = [ for r in 1..13 do
for s in 1..4 do
yield Card(enum<rank> r, enum<suit> s) ]
如果您要使用歧视的工会,则必须手动创建所有suit
和所有rank
的列表.优点是DU的模式匹配比枚举更好.
If you go for discriminated unions, you have to manually make lists of all suit
s and all rank
s. The advantage is better pattern matching of DUs than that of enums.
type suit =
| Spade
| Heart
| Club
| Diamond
type rank = | Ace | Two | Three | Four | Five | Six | Seven
| Eight | Nine | Ten | Jack | Queen | King
type Card = Card of rank * suit
let private suits = [Spade; Heart; Club; Diamond]
let private ranks = [Ace; Two; Three; Four; Five; Six; Seven;
Eight; Nine; Ten; Jack; Queen; King]
let deck = [ for rank in ranks do
for suit in suits do
yield Card(rank, suit) ]
这篇关于F#类型和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!