Knockout Clone - Discriminated Unions with F#

Monday, April 27, 2009 by gradbot

F# supports discriminated unions. This along with pattern matching makes for some short and elegant code which quite frankly is awesome. Here's a small example.

type PieceType = Breakable | Solid

member this.needsDisposing() =
match pieceType with
| Breakable -> (life <= 0)
| Solid -> false

member this.points() =
match pieceType with
| Breakable -> 1
| Solid -> 0
Here I use a property of type PieceType to both define when a piece on the board needs to be removed and if the piece returns a point when it is hit. The calling class has no knowledge of this state and filters out pieces based on the returned bool flag needsDisposing() along with adding whatever is returned by points() to the total point score.