Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid repetition in declaring similar types?

Tags:

f#

I have the following code:

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

I can define another type as follows:

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

However, there is obviously a lot of code repetition here. Is there a way to avoid this by incorporating CapturablePieces into the definition of Pieces?

like image 506
Samantha Avatar asked Apr 03 '18 10:04

Samantha


People also ask

DO is used to avoid repetition?

In formal writing it is common to avoid repeating a verb phrase by using the appropriate form of do + so: The charity converted several disused car parks into winter soup kitchens. When it had done so, it was able to provide daily meals for more than 200 people.


1 Answers

If you don't need CapturablePieces to be separable type, just some subset of particular cases, maybe it can be implemented as member? I can think of two ways:

a) Collection of capturable pieces in static member:

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

b) Boolean member:

type Pieces = Pawn | Knight | Bishop | Rook | Queen | King
    member x.IsCapturable = match x with King -> false | _ -> true
like image 139
Bartek Kobyłecki Avatar answered Nov 11 '22 22:11

Bartek Kobyłecki