-->

Adventures in F# - Enums and constructors

dev fsharp

Going over the F# Pluralsight course I learned a few more things and thought I should use them to improve my world-famous Rock-Paper-Too-Long-To-Type game.

New tidbits and improvements in the game

  • new keyword is only required when the type implements IDisposable. So no need to use them on my RPSLS object. It works exactly the same.

  • default constructor can be defined such as

new() = Car("red", 3)
  • You can access the constructor parameters anywhere in the object so there is no need to assign it to another value.

  • Assigning values to enum values makes it compatible with other.NET languages. When I assigned values to moves an interesting thing happened. I stated getting this error: Enumerations cannot have members So you can overload operators in a discriminated union in F# and you can use it in F# only but if you want your type be compatible with other CLR languages than you can only use it as a regular enum.

After I assigned the values my Move discriminated union became:

type Move = 
    | Rock = 0
    | Spock = 1
    | Paper = 2
    | Lizard = 3
    | Scissors = 4

So no more overloaded minus operator which significantly reduced the lines of code in the type. After Googling a bit I found out that generally the above values are assigned to moves the winner is determined by extracting computer number from the player number and applying modulo operator. For example: When player plays rock (0) and computer plays paper (2)

difference = player - computer = 0 - 2 = -2
result = -2 % 5 = 3 --> Python returns 3 after this operation

if result < 3 then player wins
if result >= 3 then computer wins 

Apparently in F#, -2 % 5 = -2! So I had to add 5 before applying modulo operator:

let diff = ((int)(this.PlayerMoves.Item(i) - ComputerMoves.Item(i)) + 5) % 5

Conclusion

I’m still working with the PluralSight course. In the next post I’ll examine type casting, abstract types and do bindings etc

Resources