如何避免重复声明类似的类型?

时间:2018-04-03 10:35:09

标签: f#

我有以下代码:

type CapturablePieces = Pawn | Knight | Bishop | Rook | Queen

我可以按如下方式定义另一种类型:

type Pieces = Pawn | Knight | Bishop | Rook | Queen | King

然而,这里显然有很多代码重复。有没有办法通过将CapturablePieces纳入Pieces

的定义来避免这种情况

1 个答案:

答案 0 :(得分:8)

如果你不需要CapturablePieces是可分离的类型,只是某些特定情况的子集,也许它可以作为成员实现?我可以想到两种方式:

a)静态成员中可捕捉片段的集合:

type Pieces = Pawn | Knight | Bishop | Rook | Queen | King
    static member Capturable = [Pawn; Knight; Bishop; Rook; Queen]

b)布尔成员:

type Pieces = Pawn | Knight | Bishop | Rook | Queen | King
    member x.IsCapturable = match x with King -> false | _ -> true