Partially applying functions in F#

A cool feature of a functional language like F# is the ability to partially apply a function. Take this add function:

let add x y = x + y

By partially applying this function we can create new functions like this:

let plus1 = add 1
let plus5 = add 5

The functions we have created plus1 and plus5 both have the signature int -> int. We have partially applied add to a single parameter leaving us with a function that takes one more int and returns us an int. This is a really neat idea.

Building on this if we want to do the same thing with subtract we find that it does not quite work:

let subtract x y = x - y
let minus1 = subtract 1
printfn "%i" (minus1 7)

The code above prints -6 when we wanted our minus1 function to subtract 1 from the argument given. This is because unlike with add it matters the order that you give the arguments to subtract. We have another cool trick up our sleeves to solve this:

let subtract x y = x - y
let swap f x y = f y x
let minus = swap subtract
let minus1 = minus 1
printfn "%i" (minus1 7)

The minus1 function above now does what we would expect. To make this work we defined a swap function that swaps the order of the arguments. We can then pass our subtract function to our swap function to produce a new subtract function that takes its arguments in the opposite order. We can now partially apply the new function minus with 1 to give us a new function minus1 that works how we would expect. Having functions as a first class citizen really does lead to some neat code.

Advertisements

Simple Web API OWIN host using F#

I thought it would be good to write a simple OWIN Web Api host using F# to show how easy it is to interop between the two languages and as a fun experiment. You can find all of the source code from this blog post at the FSharpWebApi github repository.

If you open the Program.fs solution in the github repository you will see the following two lines of code are reponsible for starting the web server:

let hostAddress = "http://localhost:8000"
let server = WebApp.Start(hostAddress, getAppBuilder())

The getAppBuilder function is defined in the WebServerBuilder module as follows:

let getAppBuilder() =
    let config = new HttpConfiguration()
    config.Routes.MapHttpRoute("default", "{controller}") |> ignore
    fun (appBuilder:IAppBuilder) -> appBuilder.UseWebApi(config) |> ignore

The getAppBuilder function returns a function with the signature (IAppBuilder) -> (). This signature is the same as the one expected by the first parameter of WebApp.Start. The reason for breaking this function off into its own module is so that it can be tested.

The cool thing about the Web Api Owin Self host stack is that there is a nuget package that allows you to test your server without going over http. This is great because it saves you all of the hassle of hosting an endpoint for your tests and tearing it down again. The test framework preserves all of the semantics so the requests will go through the same pipeline it’s just at the final moment they won’t go over http. The nuget package for this is Microsoft.Owin.Testing.

To use the Microsoft.Owin.Testing nuget package you have to call the static method TestServer.Create(IAppBuilder -> ()). You can see that the test server create method takes the same function that is returned by our getAppBuilder function. Which is the reason for isolating this code. The getAppBuilder function contains the logic for how your server will behave (routes, media formatters etc) so by pulling that out into a function we can test it.

As I’ve mentioned before testing in F# is very terse and to the point. Here is the full test suite for my simple hello world server:

module WebServerTests =
    let createTestServer = fun () -> TestServer.Create(new Action<IAppBuilder>(getAppBuilder()))

    [<Test>]
    let ``get /Hello should return "get - hello world"``() =
        let testServer = createTestServer()
        let client = testServer.HttpClient

        client.GetAsync("/Hello").Result.Content.ReadAsStringAsync().Result 
            |> should equal "\"get - hello world\""   

    [<Test>]
    let ``post /Hello should return "post - hello world"``() =
        let testServer = createTestServer()
        let client = testServer.HttpClient

        client.PostAsync("/Hello", new StringContent("")).Result.Content.ReadAsStringAsync().Result 
            |> should equal "\"post - hello world\"" 

To test the web server you need to get the http client that hangs off of the test server (let client = testServer.HttpClient). This gives you a special http client that is wired up directly to your web server. We can now test that we get the correct responses when issuing a get or post request to /Hello.

It is a bit of a shame that there is not an implicit conversion from Action in C# to T -> () in F#. This is the reason that the create test server line at the top of the tests is ugly. We have to new up an action of IAppBuilder and pass our getAppBuilder function into the constructor to convert our F# “action” into a C# one.

The last piece of the puzzle to make the server work is the Hello controller which can be seen below:

type HelloController () =
    inherit ApiController()

    member this.Get () = 
            "get - hello world"

    member this.Post () =
            "post - hello world"

F# shines again. Look how easy and readable this controller class is. Even if you have never written a line of F# code I reckon you could have a pretty good guess at what this controller does. The member keyword is used to provide the semantics of exposing a public property or method. The reason we need the brackets is to cause it to become a method rather than a property.

Apart from the slight ugliness of having to convert from a F# function type to a C# Action type, it is much clener in my opinion to write the code in F#. There is so much less noise. Here is the equivilent HelloController in C#:

public class HelloController : ApiController
{
    public string Get()
    {
        return "get - hello world";
    }

    public string Post()
    {
        return "post - hello world";
    }
}

All of the brackets clutter up this simple class. The brackets do not add anything to the code they just help the compiler parse it.

As already mentioned all of the code is up on a github repository for you to view at your leisure. If you have any feedback, comments or questions I would be happy to hear from you.

Manses and the Stones Hacker Rank Problem in F#

The next problem from Hacker Rank that I’m tackling in F# is a problem called Mansasa and the stones (catchy name). The basics of the problem are that you are given 2 numbers and a length and you have to give all of the distinct sums of those numbers of the lists that can be made up of length l. An example is if stone 1 has the value 2 and stone 2 has the value 4 and the length is 3 we get:

0, 2, 2 = sum 4
0, 2, 4 = sum 6
0, 4, 2 = sum 6
0, 4, 4 = sum 8

Note the problem states that we should start with 0 for each entry. This means that the distinct sums in this example would be 4 6 8 (in order).

My idea to solve this problem was to write a function that takes a list and a length and then gives you all permutations for that list of that length. In the example above if you passed this function 2 and 4 and a length of 2 it would give the 4 possible ways of arranging 2 and 4 shown above. Once I have this function I can simply sum the numbers, do a distinct and then format the result. Simples, or so I thought more on that later.

Now that I’ve got a great way to write tests for my code I started with the unit tests for the function:

module combinations =

 
module combinations =
    []
    let ``combinations for [2;3] of length 2 should be [[2;2];[2;3];[3;2];[3;3]]``() =
        combinations [2;3] 2 |> should equal [[2;2];[2;3];[3;2];[3;3]]

    []
    let ``combinations for [2;3] of length 3 should be [[2;2;2];[2;2;3];[2;3;2];[2;3;3];[3;2;2];[3;2;3];[3;3;2];[3;3;3]]``() =
        combinations [2;3] 3 |> should equal [[2;2;2];[2;2;3];[2;3;2];[2;3;3];[3;2;2];[3;2;3];[3;3;2];[3;3;3]]

    []
    let ``combinations for [1;4] of length 1 should be [[1];[4]]``() =
        combinations [1;4] 1 |> should equal [[1];[4]]

I think it is so neat that the tests describe themselves. I was stuck on writing this function in a recursive way for a little while. I’m still finding it hard to think functionally. I put this problem to my friend Sam Owens who came up with a great solution:

 
let combination list length =
    let rec solve letters len =     
        seq {
            if len = 1 then 
                for l in letters do yield [l]
            else
                let theRest = solve letters (len-1) 
                for l in letters do
                    for r in theRest do 
                        yield l::r
        }
    solve list length

I thought this solution was ingenious. Before I talk through how it works let me show you the more functional version. I created this by translating Sam’s function above to use pattern matching:

let combinations list length =
    let rec solve lst len =
        match len with
        | 1 -> lst |> Seq.map(fun x -> [x])
        | i -> lst |> Seq.map(fun l -> solve lst (len-1) |> Seq.map(fun r -> l::r)) 
                            |> Seq.collect(fun x -> x) 
    solve list length

Both of these functions are exactly the same (kudos to Sam for coming up with this way of doing it). I think the 2nd function is much more elegantly written and more readable. It’s much terser and really shows the power of F#’s pattern matching.

This function works by the fact that it knows how to print out every combination of a list of length 1. Which is shown on the first line of the match statement. To do this it simply maps out all of the elements as a list of one item. If the function is called with a length greater than one then it calls itself with length – 1 and appends the results from that on to each element in the list passed in.

With this function written composing the function to solve the whole problem was pretty straight forward:

let findMansaNumbers steps (stone1:int) (stone2:int) =
    combinations [stone1; stone2] (steps-1) |> Seq.map(fun l -> Seq.sum(l)) 
                                            |> Seq.distinct 
                                            |> Seq.sort
                                            |> fun x -> String.Join(" ", x)

All we have to do is run the combinations function passing it a list of the two stone numbers and a length. We then sum the numbers from each combination, get a distinct list of the sums, sort them in to order and then print them out in a string where each number is separted by a space. The way that F# lends itself well to composing small building blocks together makes it a fun language to program in.

Here comes the kicker. Although this solution works, it passes the first three test cases on the hacker rank problem page it then times out. The reason for this is that the number of combinations the combinations function will return is given by the formula 2^length. This is exponential growth so for big lengths the time to compute all combinations is too long. As a short aside the fact that hackerrank run the code on their server and then time out if your solution takes too long is a good thing. It stops you from being able to brute force the problems which is one of the things that plagues project Euler in my opinion.

So it’s back to the drawing board with this problem. The code is on the repository under slow solution in the MansasaAndStones.fs file in the Hacker Rank in F# repository on github.

To solve this problem it is actually very straight forward. I was just taking completely the wrong approach. If you think of the case where you have 2 stones of values 2 and 4 and are asked to find 3 steps then you can think of this as:

0, 4, 4 = sum 8 = (0*2) + (2*4)
0, 2, 4 = sum 6 = (1*2) + (1*4)
0, 2, 2 = sum 4 = (2*2) + (0*4)

So the distinct sums are 4, 6 and 8. This is calculated by having two loops, one starting and 0 and incrementing, one starting at the number of steps – 1 (as we the first step is always 0 in the problem) and then multiplying one of the loops by the first stone and one by the second.

let findNumbers steps (stone1:int) (stone2:int) =
    let list1 = [0..steps-1]
    let list2 = [0..steps-1] |> List.rev
    List.zip list1 list2 |> Seq.map(fun (x, y) -> (x*stone1)+(y*stone2))
                         |> Seq.distinct
                         |> Seq.sort
                         |> fun x -> String.Join(" ", x)

The code above is the full solution to the problem. Instead of looping twice we use the zip function to produce tuples of the loop values we can then feed this into the map function which makes the code neater. After that we just have to make sure the list is distinct (as the problem states no duplicates) and then sort it (as the problem states that the values should be in order) then we have to produce a space separated string for each answer.

I really went around the houses with this problem but I did learn some cool things in F#. Solving the combinations problem was fun and helped me practice my skills of turning C# into functional F#. Once I realised I only needed two loops I was quite happy with how nice the solution is. One thing I’m learning more and more about functional programming is that you can write really expressive beautiful code. Erik Meijer would be proud!

To look at the final solution check out the ManasaAndStones module and the solution function from the github repository. As always I would be keen to hear your feedback.