-->

Adventures in F# - MonoGame, F# and Santa!

dev fsharp

In today’s F# session I’ll examine a sample program. It helps to be inspired and learn more about real-life usage and capabilities of the language.

It’s definitely a fun game if nothing else and offers a lot to learn for F# noobs like myself!

Make Santa Jump

One thing to pay attention is when you first clone and build it gives compile errors.

Build error

To fix this you have reload the solution and restart Visual Studio.

Notes

  • use keyword has the same functionality as a let binding but adds a call to Dispose method. It’s like the using statement
  • open keyword is similar to using in C# but it can be used for other modules as well as namespaces
  • I added a source file called Game.fs and started getting the following error:

Files in libraries or multiple-file applications must begin with a namespace or module declaration, e.g. ‘namespace SomeNamespace.SubNamespace’ or ‘module SomeNamespace.SomeModule’. Only the last source file of an application may omit such a declaration.

Even though G came before P, Visual Studio didn’t automatically reorder files alphabetically like it would normally do with C#. Apparently even the order of files are important in F# (who knew?). There are even Move Up/Down options in the context menu. So I right-clicked Program.fs and moved it down so it would be the last source file in the project and it fixed the build error!

  • Properties can be defined with get and set members as below:
module Game

type Suit = 
    | Hearts 
    | Clubs 
    | Diamonds 
    | Spades

type Card(suit : Suit, value : int) = 
    let mutable faceValue = value

    member this.Value
        with get() = faceValue
        and set(value) = faceValue <- value

Resources