Category Archives: F#

C# interop with F#

Note: I’m going through draft posts that go back to 2014 and publishing where they still may have value. They may not be 100% upto date but better published late than never.

The intention of this post is to demonstrate how various bits of F# code are viewed from C# code. Obviously as both are .NET languages compiling to IL they can call one another’s code.

F# modules

Let’s start at the top, an F# module. So let’s look at a simple module

module MyModule

let squared x = x * x

The module will appears to C# as a static class and the function squared will become a static method, for example

public static class MyModule
{
  public static int squared(int x);
}

F# inferred the type to be an int

Ofcourse from C# we’ll call this function like any other static function

int result = MyModule.squared(4);

Null

The preference within F# is to use the Option type. But if you are working in C# and not wanting to include F# specific types you might prefer to still return a null. However if you are doing something like the following

match results with
| null -> null
| a -> new Thing(a)

This will fail to compiler with an error such as “The type ‘Thing’ does not have ‘null’ as a proper value.”

We can solve this by marking the Thing type with the attribute AllowNullLiteral, for example

[<AllowNullLiteral>]
type Thing() =
   // members etc.

or we might change the origina F# code to

match results with
| null -> Operators.Unchecked.defaultof<Scale>
| a -> new Thing(a)

Currying and Partial applications in F#

Note: I’m going through draft posts that go back to 2014 and publishing where they still may have value. They may not be 100% upto date but better published late than never.

Currying

Currying leads to the ability to create partial applications.

Currying is the process of taking a function with more than one arguments and turning it into single argument functions, for example

let add a b = a + b

// becomes

let add a = 
    let add' b = 
        a + b
    add'

This results in a function syntax which looks like this

val add : a:int -> (int -> int)

The bracketed int -> int shows the function which takes an int and returns and int.

Partial Applications

A partial application is a way of creating functions which have some of their arguments supplied and thus creating new functions. For example in it’s simplest form we might have

let add a b = a + b

let partialAdd a = add a 42

So, nothing too exciting there but what we can also do is, if we supply the first n arguments as per the following example

let add a b = a + b

let partialAdd = add 42

notice how we’ve removed the arguments to partialAdd but we can call the function thus

partialAdd 10 
|> printfn "%d"

we’re still supplying an argument because the function being called (the add function) requires an extra argument. The partialAdd declaration creates a new function which is partially implemented.

By declaring functions so that the last element(s) are to be supplied by a calling function we can better combine and/reuse functions.

Computational Expressions, the “standard” methods

Note: This post was written a while back but sat in draft. I’ve published this now, but I’m not sure it’s relevant to the latest versions etc. so please bear this in mind.

So in a previous post I looked at my first attempt at creating a computational expression in F#. By anyone’s level this was basic. So I figured it was time to look at all the available “standard” methods available for a computational expression. By “standard” I means those which are implciitly recognized by F# as opposed to creating custom methods.

See Computation Expressions (F#) for more info.

There are plenty of posts on this subject from Microsoft or F# for fun or profit, so why am I writing yet another post – basically just to give my perspective and to help me remember this stuff.

Let’s start with the basics, we have a type SampleBuilder defined as

type SampleBuilder() =
   // our code will be filled is as required 
   // but an example might have just the following
   member this.Bind(m, f) = f m

We shall use the builder thus

let builder = SampleBuilder()

builder {
   // expressions, such as 
   let x = 100
}

and now to the various builder methods…

Bind

let! x = 100

// translates to

builder.Bind(100, (fun x -> expression))

So as can be seen, in essence the order of the arguments is reversed. So if we were to simply duplicate the way let binding works but in a computational expression we’d write something like

member this.Bind(m, f) = 
   f m

Return and ReturnFrom

At the time of writing this, I’m a little confused as to the difference between Return and ReturnFrom. Computation expressions and wrapper types states that the Return returns a wrapped type whilst ReturnFrom returns an unwrapped type. However it is seems it’s possible to pretty much return whatever I like as shown below

member this.Return(x) = x

member this.ReturnFrom(x) = x

Return is called when we have a return in the computation expression, i.e.

builder {
   return 100
} |> printfn "%A"

and ReturnFrom is used when return! exists, i.e.

builder {
   return! 100
} |> printfn "%A"

One slightly odd thing if you’re used to C# or the likes is that we can have multiple return and/or return! in a computational expression as per

builder {
   return 100
   return! 100
} |> printfn "%A"

As per multiple yield statements, we need a Combine method implemented in our builder to combine the return values. A return does not mean the rest of the computational expression is not executed, it means that the return values are combined to produce a value at the end of the workflow. So for example

builder {
   printfn "First"
   return 100
   printfn "Second"
   return 100
} |> printfn "%A"

Assuming our Return method and Combine are as simple as the following

member this.Return(x) = 
   printfn "Return"
   x

member this.Combine(a, b) = a + b

Then our output will look like the following

First
Return
Second
Return
200

In other words, the first printfn (actually the Delay builder method is called for each printfn) is called then the Return method, then the second printfn then the second Return, then the Combine is called. In this case Combine simply adds the return values together to produce the output of the workflow.

Combine

The combine method combines multiple values – so for example if you had something like the following

builder {
   yield 100
   yield 200
} |> printfn "%A"

without a combine method you’ll get the following compiler error This control construct may only be used if the computation expression builder defines a ‘Combine’ method. Simple enough to see the problem here. So we cannot yield more than once unless we implement a combine method. Here’s an example which implements the combine by creating a list and combining elements into a new list

member this.Combine(a, b) = a @ b

If we now compile this code we’ll get another error, “This control construct may only be used if the computation expression builder defines a ‘Delay’ method”. So we need to implement a Delay method. See the example listed for Delay below…

Delay

The Delay method allows the builder to delay the evaluation of a computational expression until it’s required. For example if we yield multiple times within a computational expression the idea is to combine the yields until we’re ready to invoke something.

The example above creates a list of the yields and then in the Delay we might want to do something with those combined yields. In this example below we’ll simply use the following code

member this.Delay(f) = f()

which essentially just invokes the function passed to the delay.

Run

Whilst the Delay method is used to delay evaluation, the Run method is mean’t to use the delayed expression, i.e. it might be to run something or the likes. An example which simply turns the list created by the combine into an array instead

member this.Run(f) = Array.ofList f

this is obviously a rather simplistic example, had our builder been creating the data for a web service call, for example, possibly run would make the call for us.

For

I again must point anybody reading this section to the excellent post Implementing a builder: The rest of the standard methods where an implementation of the For method is describe, for simplicity I’ll recreate it here

member this.For(sequence:seq<_>, body) =
   this.Using(sequence.GetEnumerator(),fun enum -> 
      this.While(enum.MoveNext, 
         this.Delay(fun () -> body enum.Current)))

The Using, While and Delay methods are described elsewhere in this post.

Here’s some sample code using the For method from our computational expression block

builder {        
   for i = 1 to 10 do
      printfn "%d" i
} 

TryFinally

An implementation of the TryFinally method is fairly straightforward

member this.TryFinally(body, compensation) =
   try this.ReturnFrom(body())
   finally compensation() 

and in usage within a computational expression block, we have

builder {        
   try
      let x = 1 / 0
      printfn "should not make it to here"
   finally
      printfn "exception"
} 

In the above code, when we step into the try block we will actually enter the TryFinally method and obviously this then takes over executing the body of the code and then executing the finally block.

TryWith

Very much like the TryFinally block, we have the following implementation

member this.TryWith(body, handler) =
   try this.ReturnFrom(body())
   with e -> handler e

and an example of the computational expression block might be

builder {        
   try
      let x = 1 / 0
      printfn "should not make it to here"
   with
   | :? DivideByZeroException -> printfn "divide by zero"
} 

Using

As the name suggests, this is used for IDisposable types. Here’s a sample of it’s implementation

member thisTryFinally(body, compensation) =
   try __.ReturnFrom(body())
   finally compensation() 

member this.Using(disposable:#System.IDisposable, body) =
   let body' = fun () -> body disposable
   this.TryFinally(body', fun () -> 
      match disposable with 
      | null -> () 
      | disp -> disp.Dispose())

The Using method relates to the use! keyword and hence we might have code such as

builder {        
   use! x = new MemoryStream()
   printfn "do something with the memory stream"
} 

So at the point use! is invoked our Using method takes over. We i

While

The example of a while loop in a computational expression was lifted from “Implementing a builder: The rest of the standard methods” and I highly recommend anyone visiting this post goes and reads the computational expression series on F# for fun and profit.

So our example code is as follows

let mutable i = 0
let test() = i < 5
let inc() = i <- i + 1

let builder = SampleBuilder()

builder {        
   while test() do
      printfn "%i" i
      inc()         
} |> ignore

It’s important to note that the three let statements at the top of the source must be global or you’ll get an error along the lines of “The mutable variable ‘i’ is used in an invalid way. Mutable variables cannot be captured by closures. Consider eliminating this use of mutation or using a heap-allocated mutable reference cell via ‘ref’ and ‘!’.”

So our builder code should look something like the following

member this.Bind(m, f) = f m

member this.Return(x) = x

member this.Zero() = this.Return ()

member this.Delay(f) = f

member this.Run(f) = f()

member this.While(guard, body) =
   if not (guard()) 
   then 
      this.Zero() 
   else
      this.Bind( body(), fun () -> 
         this.While(guard, body))  

So as can be seen, in the While method we are passed the guard and the body of the while loop and as expected we need to invoke these bits of code to evaluate them. When the guard completes we invoke the Zero method which in this case simply called the Return method. If the loop has not completed we simply keep looping.

Yield and YieldFrom

We can use yield or yield! from a computational expression, but to do so we need to implement the Yield and YieldFrom methods (respectively) on the builder, otherwise we’ll be greeted with the “This control construct may only be used if the computation expression builder defines a ‘Yield’ method”, here’s an example of the yield being used from a computational expression block

builder {
   yield 100
} |> printfn "%A"

// or

builder {
   yield! 100
} |> printfn "%A"

An example of the Yield and YieldFrom methods in the builder might look like the following

member this.Yield(x) = Some x

member this.YieldFrom(x) = x

Zero

You may have noticed, if you’ve written your own builder type that something like the following

builder {
}

// or

builder {
} |> ignore

doesn’t compile, this is because a computational expression must have something within the curly braces. So if instead we write the following

builder {
   printfn "Hello"
}

We’re get an altogether different error at compile time stating This control construct may only be used if the computational expression builder defines a ‘Zero’ method. Basically a computational expression must return something, either explicitly or implicitly. In this case Zero is used for any implicit return, so we could resolve this error using

member this.Zero() = ()

or ofcourse we might implicitly return the same thing we would with an explicit return such as

member this.Return(x) = x

member this.Zero() = this.Return ()

F# currying in a little more depth

Unlike Scala, for example, F# does not use an alternate syntax to differentiate a “curry-able” function from a “non-curry-able” function. I was therefore interested in what the F# compiler does to when supplied with a function like the following

let add a b c = a + b + c

Does it really generate something like the following code?

let add a = 
    let add1 b = 
        let add2 c = 
            a + b + c
        add2
    add1

Obviously this wouldn’t be great as the code requires closures and sub-functions to be created and so would be less performant in situations where we do not require the currying capabilities.

Thankfully the F# compiler takes care of everything for us so that if we have code in our application which solely uses the add function, like this

let r = add 1 2 3

then the compiler simply generates the following, this is taken from ILSpy from the compiled code and obviously reproduced in C# which I think demonstrates pretty clearly what happens.

public static int add(int a, int b, int c)
{
   return a + b + c;
}

// therefore our call to the 
// function becomes
int r = Program.add(1, 2, 3);

Now, what happens if we start currying our functions, with code like this

let r = add 1 2 
let r1 = r 3

Here the compiler still creates the add method as before (as one would expect) but it also creates the following internal class (I’ve removed attributes to make it all a little cleaner)

internal sealed class r@9
{
   public int a;
   public int b;

   internal r@9(int a, int b)
      : this()
   {
      this.a = a;
      this.b = b;
   }

   public override int Invoke(int c)
   {
      return Program.add(this.a, this.b, c);
   }
}

// now our calling 
// code looks like this
int a = 1;
int b = 2;
FSharpFunc r2 = new r@9(a, b);
int r = (int)r2.Invoke((!0)3);

So in conclusion, if we’re not using currying on our functions then we get a “standard” function and once we start currying only then do we get the equivalent of sub-functions being created.

Using Giraffe as a service pipeline in Kestrel

In the previous post we looked at using Kestrel to run an ASP.NET Core application, now we’re going to use Giraffe to build some services.

Giraffe is an F# library to let get started by creating our application code.

  • Create Visual F# | .NET Core | Console App
  • My project is named GiraffeTest
  • Add via NuGet Giraffe and Microsoft.AspNetCore

Replace Program.fs code with the following

open Giraffe
open Microsoft.Extensions.DependencyInjection
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore

let webApp =
    choose [
        GET >=>
            choose [
                routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
            ]
    ]

type Startup() =
    member this.ConfigureServices (services : IServiceCollection) =
        services.AddGiraffe() |> ignore

    member this.Configure (app : IApplicationBuilder) =
        app.UseGiraffe webApp

[<EntryPoint>]
let main _ =
    WebHost.CreateDefaultBuilder()
        .UseKestrel()
        .UseStartup<Startup>()
        .Build()
        .Run()
    0

In the previous post we saw how to create the Kestrel server, so the code in main is exactly the same (apart from obviously being F#) which creates the server and calls the Startup class to configure our middleware. In this case we add Giraffe to the services and runs the Giraffe webApp HTTP handler.

The webApp HTTP handler is basically our filter and routing function.

Run this code up and navigate to localhost:5000/hello/World and we should get Hello World displayed.

We didn’t actually need the GET handler as by default the GET will be used, but it’s shown here to be a little more explicit in what is being implemented. We can also support POST methods using the same syntax as our GET code.

Extending our routes

Giraffe allows us to declare multiple routes which can include static pages. Let’s start off my adding an index.html page to the “Content root path” as displayed when running the application, in my case this is the folder containing Program.fs. I’m using the following index.html

<html>
    <body>
        Hello World
    </body>
</html>

Now add a new route to the route section of the webApp. i.e.

choose [
    routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
    route "/" >=> htmlFile "index.html"
]

This has now added a route for localhost:5000/ which returns the contents of the index.html file.

A list of different routes can be seen in the source for Routing.fs.

Below is an example of using some different routes

let helloName name = text (sprintf "Hello %s" name)

let webApp =
    choose [
        GET >=>
            choose [
                // case insensitive using anonymous function
                routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
                route "/"       >=> htmlFile "index.html" 
                route "/error"  >=> setStatusCode 404
                route "/ping"   >=> text "pong"
                // case sensitive use function
                routef "/hello2/%s" helloName
            ]
    ]

Return from the fish (>=>) operator can be marked as different types of result types.
The functions text, htmlFile and other response writes available here ResponseWriters.fs. These include the usual suspects such as XML and JSON. Giraffe also supports Razor, see the NuGet package Giraffe.Razor.

References

Giraffe GitHub repos.

Currying functions

Currying is probably better known within functional languages. In it’s simplest form we can view a currying as a way to declare a function and if a user of the function supplies less arguments than expected then a function is returned which takes the remaining arguments.

Let’s look at currying using a functional language such as F# first, as this really shows the usefulness of such a capability. We’ll define an add function which takes three parameters

let add a b c = a + b + c

Now we can write code such as

let r = add 1 2

Note: when we create a new function from our curried function, such as r in above, we can call this a partially applied function.

As you can see, we have not supplied all the arguments and hence r is not an integer but is instead a function which now accepts a single argument, i.e. the final argument the add function expects. Therefore we can write the following code against the returned function

let i = r 3

Now, i is an integer and contains the result of add 1 2 3 function call (i.e. the value 6).

Currying comes “built-in” syntactically in languages such as F#. We can write explicit code to demonstrate what in essence happens when we work within currying capable languages. Here’s an F# example which shows how we create functions returning functions along with closures to pass the preceding function arguments to each inner function

let add a = 
    let add1 b = 
        let add2 c = 
            a + b + c
        add2
    add1

Note: The F# compiler does NOT create the code equivalent to the above when we create functions unless the usage of the add method includes using it in a curried scenario.

The above is written in F# but you’ll notice that this same technique can easily be written in languages such as C#, Java etc. Here’s the same code in a verbose implementation in C#

public static Func<int, Func<int, int>> Add(int a) => 
   new Func<int, Func<int, int>>(b => (c => a + b + c));

Thankfully C# allows a less verbose syntax, so the above can be rewritten as

public static Func<int, Func<int, int>> Add(int a) =>
   b => (c => a + b + c);

To call such a function we’d need to write code such as

var i = Add(1)(2)(3)

This is not as elegant as the F# code (in my opinion) but does allow currying and partially applied functions in C#.

As you’d expect – another functional language, Scala, supports currying using the following syntax

def add(a : Int)(b : Int)(c : Int) = a + b + c;

val r = add(1)(2)_
// or alternate syntax
// val r = add(1)(2)(_)
val i = r(3)

Notice that we require the _ (underscore) to ignore the third argument and we need to wrap each argument within brackets (creating parameter groups) to enable the function to be curried. The missing last argument need now be enclosed within brackets.

Scala also allows us to create partially applied functions where it’s not just the last n parameters that make up the new function. For example (let’s change the argument types to a string to the output is more obvious.

def mid(a : String)(b : String)(c : String) = a + b + c;

def m = mid("Start ")(_:String)(" End")
println(m("Hello World"))
// outputs Start Hello World End

In this case we’re making a partially applied function using the curried function mid where in usage we miss out the middle parameter in the example usage. However we must also supply the type along with the _ placeholder.

Getting RESTful with Suave

I wanted to implement some microservices and thought, what’s more micro than REST style functions, executing single functions using a functional language (functional everywhere!). So let’s take a dip into the world of Suave using F#.

Suave is a lightweight, non-blocking, webserver which can run on Linux, OSX and Windows. It’s amazingly simple to get up and running and includes routing capabilities and more. Let’s try it out.

Getting Started

Create an F# application and the run Install-Package Suave via Package Manager Console.

Now, this code (below) is taken from the Suave website.

open Suave
open Suave.Filters
open Suave.Operators
open Suave.Successful

[<EntryPoint>]
let main argv = 

    let app =
        choose
            [ GET >=> choose
                [ path "/hello" >=> OK "Hello GET"
                  path "/goodbye" >=> OK "Good bye GET" ]
              POST >=> choose
                [ path "/hello" >=> OK "Hello POST"
                  path "/goodbye" >=> OK "Good bye POST" ] ]

    startWebServer defaultConfig app

    0 // return an integer exit code

Run your application and then from you favourite web browser, type in either http://localhost:8083/hello and/or http://localhost:8083/goodbye and you should see “Hello GET” and/or “Good bye GET”. From the code you can see the application also supports POST.

Let’s test this using Powershell’s Invoke-RestMethod. Typing Invoke-RestMethod -Uri http://localhost:8083/hello -Method Post and you will see “Hello POST”.

Passing arguments

Obviously invoking a REST style method is great, but what about passing arguments to the service. We’re going to need to add the import open Suave.RequestErrors to support errors. We can read parameters from the commands using HttpRequest queryParam

 let browse =
        request (fun r ->
            match r.queryParam "a" with
            | Choice1Of2 a -> 
                match r.queryParam "b" with
                | Choice1Of2 b -> OK (sprintf "a: %s b: %s" a b)
                | Choice2Of2 msg -> BAD_REQUEST msg
            | Choice2Of2 msg -> BAD_REQUEST msg)

    let app =
        choose
            [ GET >=> choose
                [ path "/math/add" >=> browse ]
            ]

    startWebServer defaultConfig browse

Disclaimer: This is literally my first attempt at such code, there may be a better way to achieve this, but I felt the code was worth recording anyway. So from our preferred web browser we can type http://localhost:8083/math/add?a=10&b=100 and you should see a: 10 b:100.

Passing JSON to our service

We can also pass data in the form of JSON. For example, we’re now going to pass JSON contain two integers to our new service. So first off add the following

open Suave.Json
open System.Runtime.Serialization

Now we’ll create the data contracts for sending and receiving our data using, these will be serialized automatically for us through the function mapLson which will see in use soon. Notice we’re also able to deal with specific types, such as integers in this case (instead of just strings everywhere).

[<DataContract>]
type Calc =
   { 
      [<field: DataMember(Name = "a")>]
      a : int;
      [<field: DataMember(Name = "b")>]
      b : int;
   }

[<DataContract>]
type Result =
   { 
      [<field: DataMember(Name = "result")>]
      result : int;
   }

Finally let’s see how we startup our server. Here we use the mapJson to map our JSON request into the type Calc from here we carry out some function (in this case addition) and the result is returned (type inference turns the result into a Result type).

startWebServer defaultConfig (mapJson (fun (calc:Calc) -> { result = calc.a + calc.b }))

Let’s test this using our Invoke-RestMethod Powershell code. We can create the JSON body for this method in the following way.

Invoke-RestMethod -Uri http://localhost:8083/ -Method Post -Body '{"a":10, "b":20}'

References

Suave Music Store
Invoke-RestMethod
Building RESTful Web Services
Building REST Api in Fsharp Using Suave

F# MVVM plumbing code

I’m trying to see how far I can go in implementing a WPF application purely in F# (and I don’t mean that third party or framework libraries must be F#, just my code). The application isn’t going to be massive or probably very complex, I’m just interested in finding the “pain points” of using F# and WPF.

In previous posts I’ve created the code to start-up an application and load the main window along with how I might assign a view model to the DataContext of the main window.

I now want to take care of the usual mundane tasks such as binding to a view model, handling property change events on the INotifyPropertyChanged interface and implementing commands using the ICommand interface.

Handling property changes and INotifyPropertyChanged

In my C# WPF projects I use a extension methods that both assign values (if a property has changed) and raises PropertyChanged events using Expression objects as opposed to “magic strings”, i.e.

public string Name
{
   get { return name; }
   set { this.RaiseAndSetIfChanged(x => x.Name, ref name, value); }
}

I wanted to have something similar in F#. Instead of extension methods, I went the base class route

type ViewModelBase() =
    let propertyChanged = Event<_, _>()
    interface INotifyPropertyChanged with
        [<CLIEvent>]
        member this.PropertyChanged = propertyChanged.Publish

    member private this.OnPropertyChanged p = propertyChanged.Trigger(this, PropertyChangedEventArgs(p))
           
    member this.RaisePropertyChanged (p : obj) =
        match p with
        | :? string as s -> 
                this.OnPropertyChanged s
        | :? Expr as e -> 
                match propertyName e with
                | Some(pi) -> 
                    this.OnPropertyChanged pi
                | None -> ()
        | :? (string array) as a ->
                a
                |> Array.iter (fun propertyName -> this.RaisePropertyChanged propertyName) 
        | :? (Expr array) as a ->
                a
                |> Array.iter (fun propertyExpression -> this.RaisePropertyChanged propertyExpression) 
        | null ->
                this.OnPropertyChanged null
        | _ -> ()

    member this.RaiseAndSetIfChanged ((p : obj), (backingField : 'b byref), newValue) =
        assert (p <> null)

        match EqualityComparer.Default.Equals(backingField, newValue) with
        | true -> false
        | false -> 
            backingField <- newValue
            this.RaisePropertyChanged p
            true

Where the propertyName functions is defined elsewhere as

let rec propertyName quotation =
    match quotation with
    | PropertyGet (_,propertyInfo,_) -> Some(propertyInfo.Name)
    | Lambda (_,expr) -> propertyName expr
    | _ -> None

Note: This function is documented Getting a Property Name as a String in F#

You’ll notice that whilst we can overload methods in an F# type, I’ve gone with pattern matching against types passed into the RaisePropertyChanged method. This just seemed tidier and allowed me to use the same function for passing a null as well (so binding on all properties should update).

This view model base class allows me to raise a property against a “magic string”, against a Expr or against an array of either (useful when I wanted to force multiple readonly properties to update).

The RaiseAndSetIfChanged function expects a non-null property p which can be a string or an Expr.

There might be a better way to do this in F#, but this is what I’ve come up with thus far.

So to use the above code in our view model we would write something like

type MyViewModel() =
    inherit ViewModelBase()

    let mutable name = ""

    member this.Name with get() = name and 
                                set(value) = 
                                    this.RaiseAndSetIfChanged (<@ fun (v : MyViewModel) -> v.Name @>, &name, value) |> ignore

The use of the Code Quotations in F# don’t look quite as good (or terse) as C# and I’m not sure if there’s a better way, but they’re still better than “magic strings”.

Commands

Next up, we need to handle ICommand. I want something akin to ActionCommand, so implemented

type Command(execute, canExecute) =
    let canExecuteChanged = Event<_, _>()
    interface ICommand with
        [<CLIEvent>]
        member this.CanExecuteChanged = canExecuteChanged.Publish
        member this.CanExecute param = canExecute param
        member this.Execute param = execute param

    new(execute) =
        Command(execute, (fun p -> true))

    member this.RaiseCanExecuteChanged p = canExecuteChanged.Trigger(this, EventArgs.Empty)

and in use with have

type MyViewModel() =
    inherit ViewModelBase()

    let mutable name = ""

    member this.Name with get() = name and 
                                set(value) = 
                                    this.RaiseAndSetIfChanged (<@ fun (v : MyViewModel) -> v.Name @>, &name, value) |> ignore

    member this.PressMe = Command(fun p -> this.Name <- "Hello " + this.Name)

Creating a WPF application in F# (a more complete solution)

In my previous post Creating a WPF application in F# I outlined how to create a very basic WPF application using F# and WPF.

I’ve now decided to combine F#, WPF and MahApps metro/modern UI look and feel. In doing so I found a flaw in the previously posted code. First off, the code works fine, but I needed to add some resources to an App.xaml and which point I realized I needed to change the code to handle this. The previous post didn’t use an App.xaml (well it was mean’t to be minimalist solution to using F# and WPF – or at least that’s my excuse).

So I will repeat some of the previous post here in defining the steps to get an F#/WPF/MahApps application up and running.

Note: Please check out the post Build MVVM Applications in F# which outlines how to use the App.xaml file, I will be repeating this here.

Okay, here we go…

  • Create a new project and select F# Application
  • This will be a console application, so next select the project properties and change the Application | Output type from Console Application to Windows Application
  • Add references to PresentationCore, PresentationFramework, System.Xaml and WindowsBase
  • Change the Program.fs to look like this
    open System
    open System.Windows
    open System.Windows.Controls
    open System.Windows.Markup
    
    [<STAThread>]
    [<EntryPoint>]
    let main argv = 
        let application = Application.LoadComponent(
                            new System.Uri("/<Your Assembly Name>;component/App.xaml", UriKind.Relative)) :?> Application
    
        application.Run()
    

    Obviously change <Your Assembly Name> to the name of your compiled assembly name.

  • Using NuGet add MahApps.Metro to the project
  • Add a new item to your project. Unfortunately there’s no XAML file (at least not in the version of Visual Studio I’m testing this on). So simply pick an XML File and give it the name App.xaml
  • In the App.xaml file place the following code
    <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 StartupUri="MainWindow.xaml">
        <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    </Application>
    
  • Now add another XML file to the project and name it MainWindow.xaml
  • In the MainWindow.xaml file replace the existing text with
    <Controls:MetroWindow  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
        Title="MainWindow" Height="350" Width="525">
        <Grid>
        </Grid>
    </Controls:MetroWindow >
    
  • Finally, select the MainWindow.xaml file in the solution explorer and change the file properties Build Action to Resource

Obviously you’ll still need to setup your view model at some point and without the ability to work with partial classes (as F# doesn’t support the concept). We have a couple of options.

I’ve played around with a few ways of doing this and the easiest is to do this in the Startup event of the Application object. In doing this we also need to handle the creation of the MainWindow, so

  • Remove the StartupUri=”MainWindow.xaml” from the App.xaml as we’re going to handle the creation and assignment in code
  • In the Program.fs file, before the application.Run() add the following code
    application.Startup
    |> Event.add(fun _ -> 
                         let mainWindow = Application.LoadComponent(new System.Uri("/WPFFSharp1Test;component/MainWindow.xaml", UriKind.Relative)) :?> Window
                         mainWindow.DataContext <- new MyViewModel()
                         application.MainWindow <- mainWindow
                         mainWindow.Show()
                         )
    

And we’re done. You should now have the styling of MahApps and the creation and setting up with the main window and the main view model.

Creating a WPF application in F#

I wanted to create a bare bones WPF application using F#. There are several templates out there to create WPF apps in F# but they just added too much code from the outset for my liking.

So here are the steps to create a basic WPF F# application

  • Create a new project and select F# Application
  • This will be a console application, so next select the project properties and change the Application | Output type from Console Application to Windows Application
  • Add references to PresentationCore, PresentationFramework, System.Xaml and WindowsBase
  • Change the Program.fs to look like this
    open System
    open System.Windows
    open System.Windows.Controls
    open System.Windows.Markup
    
    [<STAThread>]
    [<EntryPoint>]
    let main argv = 
        let mainWindow = Application.LoadComponent(
                            new System.Uri("/<Your Assembly Name>;component/MainWindow.xaml", UriKind.Relative)) :?> Window
    
        let application = new Application()
        application.Run(mainWindow)
    

    Obviously change <Your Assembly Name> to the name of your compiled assembly name.

  • Add a new item to your project. Unfortunately there’s no XAML file (at least not in the version of Visual Studio I’m testing this on). So simply pick an XML File and give it the name MainWindow.xaml
  • In the MainWindow.xaml file replace the existing text with
    <Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
        <Grid>
        </Grid>
    </Window>
    
  • Finally, select the MainWindow.xaml file in the solution explorer and change the file properties Build Action to Resource

And that’s all there is to getting a WPF F# application started.

As F# doesn’t contain all the goodness of WPF templates and code behind etc. out of the box, it still might be better to create a C# WPF application then have all the view model’s etc. in a F# application if you want to, but this is a fairly good starting point if you prefer 100% F#.

Addendum

After working this stuff out and documenting it, I came across a post from MSDN Magazine titled Build MVVM Applications in F# which not only shows a more information on the approach I’ve outlined above, but also how to use F# to create view models etc.