Showing posts with label F#. Show all posts
Showing posts with label F#. Show all posts

Tuesday, 6 January 2015

Porting WCF Service Contracts to F#

One of my goals this year is to get better at F#, by using it more, so I decided to port a simple WCF service over to F#. In this post, I will demonstrate how to port data and operation contracts over from C# to F#. Let’s start by looking at the service contract we will be porting (simplified for the purposes of this post):

[ServiceContract]
public interface IRetrieval
{
    [OperationContract]
    [FaultContract(typeof(RetrievalServiceFault))]
    ChunkResponse GetChunk(ChunkRequest request);

    [OperationContract]
    [FaultContract(typeof(RetrievalServiceFault))]
    VersionInfoResponse GetVersionInfo(VersionInfoRequest request);
}


[DataContract]
public class VersionInfoResponse
{
    [DataMember]
    public string Version { get; set; }
}

[DataContract]
public class VersionInfoRequest
{
}

[DataContract]
public class ChunkResponse
{
    [DataMember]
    public byte[] Data { get; set; }

    [DataMember]
    public bool IsEndOfFile { get; set; }
}

[DataContract]
public class ChunkRequest
{
    [DataMember]
    public string FileName { get; set; }

    [DataMember]
    public long Offset { get; set; }

    [DataMember]
    public int BytesRequested { get; set; }
}

[DataContract]
public class RetrievalServiceFault
{
    public RetrievalServiceFault(string message)
    {
        this.Message = message;
    }

    [DataMember]
    public string Message { get; private set; }
}

Attributes

First, we need to know how to put attributes on things in F#. The syntax is similar to C#, just with an extra set of angle brackets (one of the few cases where C# is more compact than F#):

[<OperationContract>]

That’s easy, but what about the FaultContract attribute we have on each operation? That takes a type as a parameter. Well F# also has a typeof function, and you put the type name in angle brackets like so:

[<FaultContract(typeof<RetrievalServiceFault>)>]

Interfaces

Now we need to know how to declare an interface in F#. There seems to be no special syntax other than to declare a type containing only abstract members. For each method, we need to provide the name, the annotated parameter list, and the type it returns. The syntax looks a little odd to C# developers at first as we are used to the return type coming at the beginning rather than the end of the method signature. It takes the form abstract MethodName : ParameterName : ParameterType –> MethodReturnType. Here’s our example

[<ServiceContract()>]
type IRetrieval =
    [<OperationContract>]
    [<FaultContract(typeof<RetrievalServiceFault>)>]
    abstract GetChunk : request : ChunkRequest -> ChunkResponse

    [<OperationContract>]
    [<FaultContract(typeof<RetrievalServiceFault>)>]
    abstract GetVersionInfo : request : VersionInfoRequest -> VersionInfoResponse

 

Data Contracts

The final piece of the puzzle is to implement the four objects that are passed as the input and output to the methods on our interface. One of the challenges is that the properties need public getters and setters, and F# likes to make properties immutable. There are a few ways of achieving this in F#, but the simplest one for this purpose seems to be to use an F# record with the mutable keyword like so:

[<DataContract>]
type VersionInfoResponse =
    { [<DataMember>] mutable Version : string }

Empty Classes

The VersionInfoRequest class had me stumped for a while, as it contains no members at all (probably a bad design choice in C#), but I eventually stumbled on a way to implement this in F#:

[<DataContract>]
type VersionInfoRequest() = 
    do()

Longs and Byte Arrays

The final challenge for me was learning how to declare the types of C# long and byte[] types. In F# these turn into int64 and array<byte> respectively. Other types, such as bool, int and string, are unchanged from C#:

[<DataContract>]
type ChunkResponse =
    {   [<DataMember>] mutable Data : array<byte>;
        [<DataMember>] mutable IsEndOfFile : bool;
     }

[<DataContract>]
type ChunkRequest =
    {   [<DataMember>] mutable FileName : string;
        [<DataMember>] mutable Offset : int64;
        [<DataMember>] mutable BytesRequested : int;
    }

 

I’ll hopefully find some time soon to do a follow-up post showing how to configure the WCF client and server in F#.

Friday, 8 August 2014

Brush up on your Languages with Pluralsight

Over the last year not only have I created a number of courses for Pluralsight, I’ve also watched a lot too. Most of the time, I’m not watching to learn a brand new technology, but as a refresher for something I’ve already used a bit. Often in just an hour or two (on 1.3x playback) you can watch a whole course and pick up loads of great tips.

I’ve found it a particularly effective way to brush up on my skills in a few programming languages that I’m semi-proficient in, but not completely “fluent” in. So here’s a few programming language related courses that I can recommend:

First, last year I was glad I watched Structuring JavaScript by Dan Whalin, as I had been hearing lots of people talking about the “revealing module pattern” and “revealing prototype pattern” but hadn’t yet properly learned what those patterns were. He explains them simply and clearly.

Another great course is Python Fundamentals by Austin Bingham and Robert Smallshire. It’s been a number of years since I did any serious Python development, so my skills had grown a bit rusty. This superbly presented course is a brilliant introduction to Python, and filled in a couple of gaps in my knowledge. They’ve got a follow-up course out as well which is undoubtedly also worth watching.

Third, several times over the years I’ve tried and failed to get to grips with PowerShell. The Everyday PowerShell for Developers course by Jim Christopher was exactly what I needed as it shows how to do the sorts of things developers will be interested in doing with PowerShell.

And finally, the F# section of the Pluralsight library is still small, but growing fast, and one fascinating course was Mark Seemann’s Functional Architecture with F#. It’s fast-moving but gives fascinating insights into how you could architect a typical line of business application in a more functional way.

Anyway, that’s enough recommendations for now. I have several other courses I want to highlight, so maybe this will become a regular blog feature. Let me know in the comments if there are any must-see courses you’ve come across.

Sunday, 3 November 2013

Finding Prime Factors in F#

After having seen a few presentations on F# over the last few months, I’ve been looking for some really simple problems to get me started, and this code golf question inspired me to see if I could factorize a number in F#. I started off by doing it in C#, taking the same approach as the answers on the code golf site (which are optimised for code brevity, not performance):

var n = 502978;
for (var i = 2; i <= n; i++)
{
    while (n%i < 1)
    {
        Console.WriteLine(i);
        n /= i;
    }
}

Obviously it would be possible to try to simply port this directly to F#, but it felt wrong to do so, because there are two mutable variables in this approach (i and n). I started wondering if there was a more functional way to do this working entirely with immutable types.

The algorithm we have starts by testing if 2 is a factor of n. If it is, it divides n by 2 and tries again. Once we’ve divided out all the factors of 2, we increment the test number and repeat the process. Eventually we get down to to the final factor when i equals n.

So the F# approach I came up with, uses a recursive function. We pass in the number to be factorised, the potential factor to test (so we start with 2), and an (immutable) list of factors found so far, which starts off as an empty list. Whenever we find a factor, we create a new immutable list with the old factors as a tail, and call ourselves again. This means n doesn’t have to be mutable – we simply pass in n divided by the factor we just found. Here’s the F# code:

let rec f n x a = 
    if x = n then
        x::a
    elif n % x = 0 then 
        f (n/x) x (x::a)
    else
        f n (x+1) a
let factorise n = f n 2 []
let factors = factorise 502978

The main challenge to get this working was figuring out where I needed to put brackets (and remembering not to use commas between arguments). You’ll also notice I created a factorise function, saving me passing in the initial values of 2 and an empty list. This is one of F#’s real strengths, making it easy to combine functions like this.

Obviously there are performance improvements that could be made to this, and I would also like at some point to work out how to make a non-recursive version of this that still uses immutable values. But at least I now have my first working F# “program”, so I’m a little better prepared for the forthcoming F# Tutorial night with Phil Trelford at devsouthcoast.

If you’re an F# guru, feel free to tell me in the comments how I ought to have solved this.