Monday, December 14, 2009

Towards FsUnit 1.0

I have been giving a lot of consideration recently to an FsUnit 1.0 release and the direction of the project. The 0.6 release was meant to steer the project more in the direction of Behavioral-Driven Development but there is already a much better project out there for F# and BDD, NaturalSpec.

FsUnit 1.0 will instead be geared for more classical unit-testing and it now has two explicit goals: 1) to make unit-testing with F# more functional in nature and 2) to leverage existing unit-testing frameworks while at the same time exploring new possibilities offered by the F# language.

The target audience for this project is the F# developer (new and veteran alike) who wishes to use the same unit-testing framework that they’re already knowledgeable about: NUnit, MbUnit, xUnit, and MsTest. The new 0.9 release supports only NUnit but the others will be added soon.

The core syntax is pretty much the same as it has always been:

1 |> should equal 1

1 |> should not (equal 2)

[1] |> should contain 1

true |> should be True

But tests are once again contained within a test fixture and executed with a test runner. Here is the code for one of the project examples (UPDATE: removed non-standard use of self-identifier per reader's comments. Thanks, Alan!):

type LightBulb(state) =
member x.On = state
override x.ToString() =
match x.On with
| true -> "On"
| false -> "Off"

[<TestFixture>]
type ``Given a LightBulb that has had its state set to true`` ()=
let lightBulb = new LightBulb(true)

[<Test>] member test.
``when I ask whether it is On it answers true.`` ()=
lightBulb.On |> should be True

[<Test>] member test.
``when I convert it to a string it becomes "On".`` ()=
string lightBulb |> should equal "On"

[<TestFixture>]
type ``Given a LightBulb that has had its state set to false`` ()=
let lightBulb = new LightBulb(false)

[<Test>] member test.
``when I ask whether it is On it answers false.`` ()=
lightBulb.On |> should be False

[<Test>] member test.
``when I convert it to a string it becomes "Off".`` ()=
string lightBulb |> should equal "Off"

I’m curious as to what people think about the use of back-ticked method names. I, for one, find it very helpful to be able to write in plain prose instead of CamelCase’d or snake_case’d method names.

Stay tuned to this blog for more information as FsUnit reaches a 1.0 release.

Monday, January 26, 2009

F# and WCF: Data Contracts

F# offers the WCF developer a number of options for defining data contracts. You can use standard classes, constructed classes, or record types to define your data contracts. The key thing to remember is that the DataContractSerializer requires writeable properties. Let's take a look at a simple data contract defined in each of the three ways mentioned.

Standard Types

[<DataContract>]
type MyDataContract =
val mutable x : string

new() = { x = "" }

[<DataMember>]
member this.MyDataMember
with get() = this.x
and set v = this.x <- v


Constructed Types

[<DataContract>]
type MyDataContract() =
let mutable x = ""

[<DataMember>]
member this.MyDataMember
with get() = x
and set v = x <- v


Record Types

[<DataContract>]
type MyDataContract =
{ [<DataMember>] mutable MyDataMember : string }


Of the three, I prefer to use record types to define my data contracts. A record type mirrors the intention behind defining a data contract where we are simply declaring a set of data fields by name and type. If you've used the XmlSerializer much, you are probably aware of the default constructor requirement. This restricted the use of record types since they do not get a default constructor. Thankfully, that restriction does not apply with the DataContractSerializer. In addition, you can remove the DataContract and DataMember attributes from your type definition if you are using .NET 3.5 Service Pack 1 although I wouldn't recommend that you do this on a routine basis.

You should use the DataContract attribute to control the namespace and name of your contract. Thus, a good data contract in F# would look something like this:
[<DataContract(
Namespace = "http://schemas.vernagus.blogspot.com/01/2009",
Name = "MyDataContract")>]
type MyDataContract =
{ [<DataMember>] mutable MyDataMember : string }


When we create an instance of our contract and serialize it, we get the following:
<MyDataContract xmlns="http://schemas.vernagus.blogspot.com/01/2009"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<MyDataMember>my value</MyDataMember>
</MyDataContract>


In my next post I will explore more advanced data contract concepts like collections and enumerations.

Monday, January 19, 2009

F# and WCF Examples

Ted Neward recently wrote about using F# to write WCF services. I share his enthusiasm; so much so that I'm using F# to write examples as I study for MCTS 70-503.

Good examples are hard to find. Most of the time books will give incomplete, or worse, erroneous examples. I have striven to boil each example down to just the essentials needed to get it to run. The examples use F# Interactive and each example is a fully encapsulated, self-sufficient demonstration of some WCF concept. To run an example, simply type fsi --exec <script name>. You can see my examples here: http://code.google.com/p/wcf-examples/source/browse/#svn/trunk/FSharpExamples

I am planning to run a series of posts based on my experience in using F# to write WCF services. Stay tuned for that!

Thursday, September 18, 2008

Programming with State in F# (Part 2)

In my last post, I talked about the contrast between F# where state is locked by default and your run-of-the-mill imperative language where it is very difficult to lock state. We also saw that F# allows us to explicitly use mutable state when we choose to do so but the point is that programmer must make an explicit choice. The theme of this series of posts is that F#'s answer to the "whether to use state or not to use state" question is the best: we try not to use state where we can get away with it but when we have to use state we make that decision explicitly and carefully.

I just want to talk about one example from the F# Core library. Here is an example from the Seq module:
let length (ie : seq<'a>)    = 
use e = ie.GetEnumerator()
let mutable state = 0
while e.MoveNext() do
state <- state + 1;
state
The length function takes any sequence and returns an int. The first line of the function retrieves the enumerator for the sequence. The second line declares a mutable identifier clearly labeled state. The rest of the function simply moves through the enumerator incrementing the count. Finally, the function returns the final count. Do the internals of the length function surprise you? This example is very similar to how a length might be determined in an imperative context and it highlights my favorite feature of F#: it's your choice. You certainly can implement length with a recursive function and an accumulating value but would it be as fast as the version shown above? Would it be as easy to understand? You decide.

Choices abound when using F# and one of the most important choices you can make will be whether or not to use state. The point of these last two posts are to highlight this quality of F#. State is generally discouraged but it is always available should you choose to use it.

Wednesday, September 17, 2008

Programming with State in F# (Part 1)

There is frequent talk these days about the use of state in programs--how to limit it and whether it should be used at all. The rising importance of concurrency and functional languages have a lot to do with this but state is hardly going to go away any time soon. For instance, Kent Beck writes favorably about state in his recent book, Implementation Patterns:
I think state is a valuable metaphor for us since our brains are structured and conditioned to deal with changing state. Single assignment or variableless programming forces us to discard too many effective thinking strategies to be an attractive choice.
Kent goes on to show his readers a set of patterns that can be used to manage and communicate state in a safe and effective manner. I agree that state is a valuable metaphor in programming but what is a programmer to do if they also see value in single assignment or "stateless" programming? I think F# offers the most compelling answer to this question and I'll explain why.

You declare a value in F# with the let keyword:
> let x = 1;;

val x : int
We can later retrieve the value, 1, using our identifier, x:
> x;;

val it : int = 1
Suppose, however, that we wanted to change the value assigned to x. We would use the assignment operator like so:
> x <- 2;;

x <- 2;;
^^^^^^^

stdin(13,1): error FS0027: This value is not mutable.
As you can see, identifiers are immutable by default in F#. Once declared, they cannot be changed. This behavior extends to more complex value types. Consider this example:
> open System.Drawing;;
> let p1 = new Point(0,0);;

val p1 : Point

> p1.X <- 1;;

p1.X <- 1;;
^^^

stdin(24,1): error FS0191: A value must be local and mutable in order to mutate
the contents of a value type, e.g. 'let mutable x = ...'.
Even though the X property of System.Drawing.Point is settable, F# treats our Point as if it is immutable. We can see how the default behavior of F# compels the programmer to limit his use of state; that's just the way that it should be. By contrast, it takes a lot of forethought to limit state in an imperative language.

You can opt-in to the use of state by using the mutable keyword:
> let mutable p2 = new Point(0,0);;

val mutable p2 : Point

> p2.X;;

val it : int = 0

> p2.X <- 1;;

val it : unit = ()

> p2.X;;

val it : int = 1
When you declare an identifier as mutable, you get a variable just like you may be used to in C# or Visual Basic. You can even change the reference entirely:
> p2 <- new Point(1,1);;

val it : unit = ()

> p2;;

val it : Point = {X=1,Y=1} {IsEmpty = false;
X = 1;
Y = 1;}
To conclude this post, I hope to have shown some very basic examples of how F# forces you to think about where you are using state and why. This is a very good thing and in my next post, we will explore the use of state in functions and types.

Monday, September 8, 2008

Book Samples in F#

I'm fairly new to functional programming but I am on my second reading of a couple of great titles: The Little MLer and Purely Functional Data Structures.

Both of these books contain code samples in Standard ML (SML) (the latter contains a Haskell appendix). Readers with a background in functional languages would have no problem translating from SML to OCaml and F# but for newcomers this can be a very complicated endeavor and it greatly detracts from the reading.

When I first read these books I failed to find any code examples in F# and I even struggled to find OCaml samples based on the books. In order to encourage newcomers to F# to take up a study of functional programming, I have started a project on Google Code to address this need. The project will host relative ports of code samples from various books.

I do not intend for the ports to be literal translations. There are, for instance, constructs in SML that simply aren't available in F#. But the samples should convey the spirit of the book even if they use different means to achieve that end.

If you have samples or suggestions, corrections, or improvements for the samples, please get in touch!

Thursday, September 4, 2008

FsUnit 0.6.0

I've just wrapped up a 0.6.0 release of the FsUnit specification framework for F#! I'm really starting to appreciate the benefits of writing specifications or tests in a functional language. I hope that this project convinces others in the same way.

The F# 1.9.6.0 release is a very important release. F# developers get much deeper support in Visual Studio, for one, and this led a complete overhaul of the tests behind FsUnit. I prefer to do test-driven development when I can, thus a rewrite of the tests meant a rewrite of the framework itself. Everything ended up pretty much the same as it was in the previous release (0.5.0) with a couple of minor changes.

The first important change was better messages with failures and errors. The previous release didn't always provide informative messages. With this release, you should always receive enough information to identify the problem.

The second important change involves better support for exceptions that may occur when running your specs. Exceptions should not prevent any other specification from running and should one occur, you should get a full stack trace along with the exception message.

Finally, there was a slight change to the spec function. Use of spec still evaluates your specification, but it no longer adds it to the internal mutable results collection. I wanted to leave mutable state out of the framework wherever possible, thus, spec now returns a string * Result pair and programmers can choose to use or not to use state in their specifications. If you're lazy like me, you can use the specs function to have FsUnit track your results for you.

See the project home page, the project wiki, or the included examples for more information about the project. Please check it out and let me know how I can make it better!