有没有一种更简单的方法来使用F#初始化这副牌?
let create() = [ 0..12 ]
type Suit =
| Spades of list<int>
| Hearts of list<int>
| Clubs of list<int>
| Diamonds of list<int>
let spades = create() |> Spades
let hearts = create() |> Hearts
let clubs = create() |> Clubs
let diamonds = create() |> Diamonds
具体来说,我想简化这四种套装的初始化。 有更简单的方法吗?
我可以列举这个有区别的联盟的类型并将其分配给某些“套牌”结构吗?
注:
我是F#的新手。如果这个问题似乎无知,请原谅我。
答案 0 :(得分:5)
我认为没有更简洁的方式,但我也不会模仿这样的扑克牌,因为它无法帮助使非法国家无法代表。举个例子,我可以这样做:
> Spades [-1; 10; 100];;
val it : Suit = Spades [-1; 10; 100]
这甚至意味着什么?
type Suit = Diamonds | Hearts | Clubs | Spades
type Face =
| Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten
| Jack | Queen | King | Ace
type Card = { Suit: Suit; Face: Face }
这样您就可以表达任何有效的卡:
> { Suit = Spades; Face = Ace };;
val it : Card = {Suit = Spades;
Face = Ace;}
另一方面,你无法表达invalid
张卡片:
> { Suit = Spades; Face = Hundred };;
{ Suit = Spades; Face = Hundred };;
------------------------^^^^^^^
stdin(4,25): error FS0039: The value or constructor 'Hundred' is not defined
初始化在这个模型中看起来有点麻烦,但另一方面,下面的deck
是一个不可变的值,所以一旦定义了,你就可以重新使用它了再一次。
let deck = [
{ Suit = Diamonds; Face = Two };
{ Suit = Diamonds; Face = Three };
{ Suit = Diamonds; Face = Four };
{ Suit = Diamonds; Face = Five };
{ Suit = Diamonds; Face = Six };
{ Suit = Diamonds; Face = Seven };
{ Suit = Diamonds; Face = Eight };
{ Suit = Diamonds; Face = Nine };
{ Suit = Diamonds; Face = Ten };
{ Suit = Diamonds; Face = Jack };
{ Suit = Diamonds; Face = Queen };
{ Suit = Diamonds; Face = King };
{ Suit = Diamonds; Face = Ace };
{ Suit = Hearts; Face = Two };
{ Suit = Hearts; Face = Three };
{ Suit = Hearts; Face = Four };
{ Suit = Hearts; Face = Five };
{ Suit = Hearts; Face = Six };
{ Suit = Hearts; Face = Seven };
{ Suit = Hearts; Face = Eight };
{ Suit = Hearts; Face = Nine };
{ Suit = Hearts; Face = Ten };
{ Suit = Hearts; Face = Jack };
{ Suit = Hearts; Face = Queen };
{ Suit = Hearts; Face = King };
{ Suit = Hearts; Face = Ace };
{ Suit = Clubs; Face = Two };
{ Suit = Clubs; Face = Three };
{ Suit = Clubs; Face = Four };
{ Suit = Clubs; Face = Five };
{ Suit = Clubs; Face = Six };
{ Suit = Clubs; Face = Seven };
{ Suit = Clubs; Face = Eight };
{ Suit = Clubs; Face = Nine };
{ Suit = Clubs; Face = Ten };
{ Suit = Clubs; Face = Jack };
{ Suit = Clubs; Face = Queen };
{ Suit = Clubs; Face = King };
{ Suit = Clubs; Face = Ace };
{ Suit = Spades; Face = Two };
{ Suit = Spades; Face = Three };
{ Suit = Spades; Face = Four };
{ Suit = Spades; Face = Five };
{ Suit = Spades; Face = Six };
{ Suit = Spades; Face = Seven };
{ Suit = Spades; Face = Eight };
{ Suit = Spades; Face = Nine };
{ Suit = Spades; Face = Ten };
{ Suit = Spades; Face = Jack };
{ Suit = Spades; Face = Queen };
{ Suit = Spades; Face = King };
{ Suit = Spades; Face = Ace }; ]
虽然这看起来很乏味,但你只需写一次。由于deck
是一个值,因此您可以将其设为属于模块的值。客户可以简单地使用这个值,而不必自己初始化一个套牌。